Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MySingleLinkedList {
- Element head;
- Element tail;
- public MySingleLinkedList(){
- this.head = null;
- this.tail = null;
- }
- public void append(Element e){
- if (this.head == null){
- this.head = e;
- }
- else{
- this.tail.next = e;
- }
- this.tail = e;
- }
- public void prepend(Element e){
- if (this.head == null){
- this.tail = e;
- }
- else{
- e.next = this.head;
- }
- this.head = e;
- }
- public void insertBefore(Element e, int n){
- int counter = 0;
- Element previous = head;
- Element current = head.next;
- while (counter+1 < n){
- previous = current;
- current = current.next;
- counter++;
- }
- e.next = current;
- previous.next = e;
- }
- public void insertAfter(Element e, int n){
- int counter = 0;
- Element previous = this.head;
- Element current = this.head.next;
- while (counter < n){
- previous = current;
- current = current.next;
- counter++;
- }
- e.next = current;
- previous.next = e;
- }
- public void extractFirst(){
- if(this.head == null){
- System.out.println("Error");
- }
- this.head = this.head.next;
- if(this.head == null){
- System.out.println("Error");
- }
- }
- public void extractLast(){
- if (this.tail == null){
- System.out.println("Error");
- }
- if (this.head == this.tail){
- this.head = this.tail = null;
- }
- else{
- Element previous = this.head;
- while(previous.next != null){
- previous = previous.next;
- }
- previous.next = null;
- this.tail = previous;
- }
- }
- public int countNodes(){
- int counter = 0;
- Element first = this.head;
- while(first != null){
- counter++;
- first = first.next;
- }
- return counter;
- }
- public int searchNode(Object obj){
- int counter = 0;
- Element first = this.head;
- while(first != null){
- if (first.data.equals(obj)){
- counter++;
- }
- first = first.next;
- }
- return counter;
- }
- public void display(){
- Element start = this.head;
- while (start != null){
- start.print();
- start = start.next;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement