java - How to append a Linked List to back of another? -
i've implemented own linked list type of info construction i'm running problem when want append 1 linked list without iterating on anything.
here illustration output wanted
public class mylist{ public static void main(string[] args){ mylist list1 = new mylist(3); mylist list2 = new mylist(4); system.out.println(list1); //0 1 2 system.out.println(list2); //0 1 2 3 list1.add(list2); system.out.println(list1); //0 1 2 0 1 2 3 system.out.println(list2); //0 1 2 3 } private class node{ public int data; public node next; public node(int data){ this.data = data; } } public node head; public node tail; public mylist(int length){ for(int = 0; < length; i++){ add(new node(i)); } } public void add(node node) { if (head == null) { //insert first node head = node; tail = node; } else { //add node end tail.next = node; tail = tail.next; } } //problem! public void add(mylist list) { } @override public string tostring(){ string result = ""; for(node iter = head; iter != null; iter = iter.next){ result += iter.data + " "; } homecoming result; } }
when list2 added list1, want list1 extended without breaking original list2. can't see how without iterating on though. trivial iterate on list2 in add together method , add together each node end individually doesn't sense right linked lists.
can give me advice on how efficiently
you need 2 things:
settail.next
of first list
head
of 2nd list
. and re-assign tail
of 2nd list
tail
of 1st list
so, how method should like:
public void add(mylist list) { this.tail.next = list.head; this.tail = list.tail; }
and should improve name method extend
. shows intent of method more clearly.
java data-structures linked-list
No comments:
Post a Comment