Showing posts with label Linked List. Show all posts
Showing posts with label Linked List. Show all posts

Wednesday, January 14, 2015

LRU Cache (LeetCode Data Structure)

Question: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and set.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
set(key, value) - Set or insert the value if the key is not already present. When the cache reached its capacity, it should invalidate the least recently used item before inserting a new item.

Idea: Use a bi-directional linked list to store the inserted data. At the same time use a hashmap<key, node> to achieve O(1) access. Whenever a key is visited or modified, move it out of the bi-directional linked list, then insert it to the tail of the list. Whenever an insertion is required and the capacity is full, remove the node at the head.

Time: O(1) Space: O(n)

Code:
 public class LRUCache {  
   class Node{  
     int key;  
     int val;  
     Node prev;  
     Node next;  
     public Node(int key,int val)  
     {  
       this.key=key;  
       this.val=val;  
       this.prev=null;  
       this.next=null;  
     }  
   }  
   public int capacity;  
   public HashMap<Integer,Node> keyToNode;  
   public Node head;  
   public Node tail;  
   public LRUCache(int capacity) {  
     this.capacity=capacity;  
     keyToNode=new HashMap<Integer,Node>();  
     head=new Node(-1,-1);  
     tail=new Node(-1,-1);  
     head.next=tail;  
     tail.prev=head;  
   }  
   public int get(int key) {  
     if(keyToNode.containsKey(key)==false)  
       return -1;  
     Node tmp=keyToNode.get(key);  
     tmp.prev.next=tmp.next;  
     tmp.next.prev=tmp.prev;  
     moveToTail(tmp);  
     return keyToNode.get(key).val;  
   }  
   public void set(int key, int value) {  
     if(get(key)!=-1)  
     {  
       keyToNode.get(key).val=value;  
       return;  
     }  
     if(keyToNode.size()==capacity)  
     {  
       keyToNode.remove(head.next.key);  
       head.next=head.next.next;  
       head.next.prev=head;  
     }  
     Node newNode=new Node(key,value);  
     keyToNode.put(key,newNode);  
     moveToTail(newNode);  
   }  
   public void moveToTail(Node cur)  
   {  
     cur.prev=tail.prev;  
     tail.prev=cur;  
     cur.prev.next=cur;  
     cur.next=tail;  
   }  
 }  

Tuesday, January 6, 2015

Swap Nodes in Pairs (LeetCode Linked List)

Question: Given a linked list, swap every two adjacent nodes and return its head.
For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.
Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

Idea: I used recursion. First recursively swap the sub-list starting from head.next.next. Then swap head.next and head.

Time: O(n) Space: O(1)

Code: 
 public class Solution {  
   public ListNode swapPairs(ListNode head) {  
     if(head==null||head.next==null)  
       return head;  
     head.next.next=swapPairs(head.next.next);  
     ListNode newHead=head.next;  
     head.next=head.next.next;  
     newHead.next=head;  
     return newHead;  
   }  
 }  

Sort List (LeetCode)

Question: Sort a linked list in O(n log n) time using constant space complexity.

Idea: I used merge sort. If the list is longer than 2, split it to two halves at length/2, then sort the two halves individually, finally merge. I implemented a version with an extra parameter length to indicate the current length of the list. Therefore we do not need to calculate the length when a new recursion is evolved. This will not reduce the time complexity in big O notation, but it will make the algorithm to run faster in reality.

Time: O(nlgn) Space: O(lgn) (Since we need a stack to store the pointers when we keep splitting the list to halves until the real sort begins when the list has less than 3 nodes.

Code:
 public class Solution {  
   public ListNode sortList(ListNode head) {  
     int len=getLength(head);  
     return mergeSort(head,len);  
   }  
   public ListNode mergeSort(ListNode head,int length)  
   {  
     if(length<=1)  
       return head;  
     if(length==2)  
     {  
       if(head.val<=head.next.val)  
         return head;  
       ListNode dummy=new ListNode(0);  
       dummy.next=head.next;  
       head.next=null;  
       dummy.next.next=head;  
       return dummy.next;  
     }  
     ListNode pre=head;  
     for(int i=0;i<length/2-1;i++)  
       pre=pre.next;  
     ListNode secondHead=pre.next;  
     pre.next=null;  
     return merge(mergeSort(head,length/2),mergeSort(secondHead,length-length/2));  
   }  
   public ListNode merge(ListNode head1,ListNode head2)  
   {  
     if(head1==null)  
       return head2;  
     if(head2==null)  
       return head1;  
     ListNode dummy=new ListNode(0);  
     ListNode cur=dummy;  
     while(head1!=null&&head2!=null)  
     {  
       int val1=head1.val;  
       int val2=head2.val;  
       if(val1<=val2)  
       {  
         cur.next=head1;  
         head1=head1.next;  
       }  
       else  
       {  
         cur.next=head2;  
         head2=head2.next;  
       }  
       cur=cur.next;  
     }  
     if(head1!=null)  
       cur.next=head1;  
     if(head2!=null)  
       cur.next=head2;  
     return dummy.next;  
   }  
   public int getLength(ListNode head)  
   {  
     int counter=0;  
     while(head!=null)  
     {  
       counter+=1;  
       head=head.next;  
     }  
     return counter;  
   }  
 }  

Rotate List (LeetCode Linked List)

Question: Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

Idea: Since k may be larger than the length of the list, we first need to know k%length by using a pointer to traverse the linked list and reset to the head if the pointer reaches null. Another way is to measure the length of the list first, then calculate k%length. The worst case time complexity is the same.

Then we split the list to two lists at the rotate position. The new head is the head of the second sublist. The end of the new list is the node right before the rotate position, set it to null.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode rotateRight(ListNode head, int n) {  
     if(head==null || head.next==null || n==0)  
       return head;  
     ListNode faster=head;  
     ListNode slower=head;       
     for(int i=0;i<n;i++)  
     {  
       if(faster==null)  
         faster=head;  
       faster=faster.next;  
     }  
     if(faster==null)  
       return head;  
        while(faster.next!=null)  
        {  
             faster=faster.next;  
             slower=slower.next;  
     }  
     ListNode newHead=slower.next;  
     faster.next=head;  
     slower.next=null;  
     return newHead;  
   }  
 }  

Monday, January 5, 2015

Reverse Nodes in k-Group (LeetCode Linked List)

Question: Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.
If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.
You may not alter the values in the nodes, only nodes itself may be changed.
Only constant memory is allowed.
For example,
Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

Idea: Recursion. First locate the head of next run, the k+1'th node. Then reverse the first k nodes. After the reverse, let the k'th node's next point to the result of the next run.

Time: O(n) Space: O(n) (since we need a stack to store all the forgoing last pointers, e.g. at k, 2k, 3k)

Code:
 public class Solution {  
   public ListNode reverseKGroup(ListNode head, int k) {  
     if(head==null||head.next==null)  
       return head;  
     ListNode nextHead=head;  
     for(int i=0;i<k;i++)  
     {  
       if(nextHead==null)  
         return head;  
       nextHead=nextHead.next;  
     }  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode pre=dummy.next;  
     ListNode cur=pre.next;  
     for(int i=0;i<k-1;i++)  
     {  
       pre.next=cur.next;  
       cur.next=dummy.next;  
       dummy.next=cur;  
       cur=pre.next;  
     }  
     pre.next=reverseKGroup(nextHead,k);  
     return dummy.next;  
   }  
 }  

Reverse Linked List II (LeetCode Linked List)

Question: Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

Idea: First add a dummy head since m may be 1. Then find the node m-1, which is right before the section needed to be reversed. Then for each node from m+1 to n, insert it right after the node m-1. The that section is reversed.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode reverseBetween(ListNode head, int m, int n) {  
     if(m==n)  
       return head;  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode pre=dummy;  
     for(int i=0;i<m-1;i++)  
       pre=pre.next;  
     ListNode head2=pre;  
     pre=head2.next;  
     ListNode cur=pre.next;  
     for(int i=m;i<n;i++)  
     {  
       pre.next=cur.next;  
       cur.next=head2.next;  
       head2.next=cur;  
       cur=pre.next;  
     }  
     return dummy.next;  
   }  
 }  

Reorder List (LeetCode Linked List)

Question: Given a singly linked list L: L0→L1→…→Ln-1→Ln,
reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…
You must do this in-place without altering the nodes' values.
For example,
Given {1,2,3,4}, reorder it to {1,4,2,3}.

Idea: First split the linked list to two half at point Ln/2. Then reverse the second half. Then we have a list like this:
L0 -> L1 ->... ->Ln/2-> Ln/2+1 <-Ln/2+2... <-Ln, where Ln/2+1.next=null. Then we merge the list from the two ends L0 and Ln one by one, e.g. L0 -> Ln -> L1 -> Ln-1 -> ... -> Ln/2 -> Ln/2+1.

Time: O(n) Space: O(n) (since the reverse of the second half is recursion which needs a O(n) stack).

Code: 
 public class Solution {  
   public ListNode reverseList(ListNode head)  
   {  
     if(head==null||head.next==null)  
       return head;  
     reverseList(head.next).next=head;  
     head.next=null;  
     return head;  
   }  
   public void reorderList(ListNode head) {  
     if(head==null||head.next==null)  
       return;  
     ListNode slower=head;  
     ListNode faster=head;  
     while(faster.next!=null)  
     {  
       faster=faster.next;  
       slower=slower.next;  
       if(faster.next!=null)  
         faster=faster.next;  
     }  
     reverseList(slower);  
     ListNode cur=head;  
     while(faster!=slower)  
     {  
       ListNode fasterTmp=faster.next;  
       faster.next=cur.next;  
       cur.next=faster;  
       faster=fasterTmp;  
       cur=cur.next.next;  
     }  
   }  
 }  

Remove Nth Node From End of List (LeetCode Linked List)

Question: Given a linked list, remove the nth node from the end of list and return its head.
For example,
   Given linked list: 1->2->3->4->5, and n = 2.
   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note:
Given n will always be valid.
Try to do this in one pass.

Idea: First add a dummy head at the front of the input linked list, since the original head may be the node to be removed. Then use two pointers "slower" and "faster" to traverse the list. Let the faster run n steps, then let the faster and the slower run simultaneously. Since the faster is n steps ahead of the slower, when faster.next reach the end (null), the slower.next is the nth node which needs to be removed.

Time: O(n) Space: O(1)

Code: 
 public class Solution {  
   public ListNode removeNthFromEnd(ListNode head, int n) {  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode slower=dummy;  
     ListNode faster=dummy;  
     for(int i=0;i<n;i++)  
       faster=faster.next;  
     while(faster.next!=null)  
     {  
       slower=slower.next;  
       faster=faster.next;  
     }  
     slower.next=slower.next.next;  
     return dummy.next;  
   }  
 }  

Remove Duplicates from Sorted List II (LeetCode Linked List)

Question: Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

Idea: First add a dummy node at the front of the input list, since the head node may also be removed.  Then use a pointer "cur" to traverse the list. For each "cur", check whether the next a few elements are duplicates by starting an runner from cur.next.next and compare the value with cur.next. If the runner ran 0 step, means no duplicates, otherwise skip the nodes the runner has passed.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode deleteDuplicates(ListNode head) {  
     if(head==null||head.next==null)  
       return head;  
     ListNode dummy=new ListNode(0);  
     dummy.next=head;  
     ListNode cur=dummy;  
     while(cur.next!=null)  
     {  
       ListNode start=cur.next;  
       ListNode runner=start.next;  
       while(runner!=null&&runner.val==start.val)  
         runner=runner.next;  
       if(start.next=runner)  
         cur=start;  
       else  
         cur=runner;  
     }  
     return dummy.next;  
   }  
 }  

Remove Duplicates from Sorted List (LeetCode Linked List)

Question: Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

Idea: Use a pointer "pre" to traverse the whole list. Whenever pre.next.val==pre.val, skip the next node by pre.next=pre.next.next; otherwise push pre forward one step pre=pre.next.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode deleteDuplicates(ListNode head) {  
     if(head==null||head.next==null)  
       return head;  
     ListNode pre=head;  
     while(pre.next!=null)  
     {  
       if(pre.next.val==pre.val)  
         pre.next=pre.next.next;  
       else  
         pre=pre.next;  
     }  
     return head;  
   }  
 }  

Partition List (LeetCode Linked List)

Question: Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.
You should preserve the original relative order of the nodes in each of the two partitions.
For example,
Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

Idea: Two pointers.
1) First add a dummy head in the beginning of the linked list to deal with the cases when the current head>= x that a <x node needs to be added before the current head.
2) Use two pointers: lessTail and pre. lessTail is to remember the last digit <x. pre is used to traverse the list.
3) When pre.next is a value >=x, just push pre forward.
4) When pre.next is a value <x, we need to swap it to right behind lessTail. As in the example in the question, when pre=3, pre.next=2, we need to swap the 2 to the back of 1 (lessTail). In this case, the element 2 is cut from the list and moved to the back of 1. So push lessTail forward by 1 step, but keep pre=3 the same since pre.next=5 is right the node we are going to check in the next run.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode partition(ListNode head, int x) {  
     if(head==null||head.next==null)  
       return head;  
     ListNode dummy=new ListNode(Integer.MIN_VALUE);  
     dummy.next=head;  
     ListNode lessTail=dummy;  
     while(lessTail.next!=null&&lessTail.next.val<x)  
       lessTail=lessTail.next;  
     if(lessTail.next==null)  
       return dummy.next;  
     ListNode pre=lessTail.next;  
     while(pre.next!=null)  
     {  
       if(pre.next.val<x)  
       {  
         ListNode cur=pre.next;  
         pre.next=pre.next.next;  
         cur.next=lessTail.next;  
         lessTail.next=cur;  
         lessTail=lessTail.next;  
       }  
       else  
       {  
         pre=pre.next;  
       }  
     }  
     return dummy.next;  
   }  
 }  

Merge k Sorted Lists (LeetCode Linked List)

Question:  Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Idea: I tried to make use of merge 2 sorted linked lists. However it gets exceed time limits error in Java. So I have to use heap sort. First insert all the heads of the lists to the heap. Pop the root of the heap and insert the root's next to the heap, until the heap becomes empty.

Time: O(n^2lgn) Space: O(n). Assume we have n lists each of which has n elements.

Code:
 public class Solution {  
   public Comparator<ListNode> comp=new Comparator<ListNode>()  
   {  
     public int compare(ListNode left,ListNode right)  
     {  
       if(left==null)  
         return 1;  
       else if(right==null)  
         return -1;  
       else  
         return left.val-right.val;  
     }  
   };  
   public ListNode mergeKLists(List<ListNode> lists) {  
     if(lists.size()==0)   
       return null;  
     Queue<ListNode> heap=new PriorityQueue<ListNode>(lists.size(),comp);  
     for(ListNode head:lists)  
     {  
       if(head!=null)  
         heap.add(head);  
     }  
     ListNode dummy=new ListNode(0);  
     ListNode tail=dummy;  
     while(!heap.isEmpty())  
     {  
       ListNode tmp=heap.poll();  
       tail.next=tmp;  
       tail=tail.next;  
       if(tmp.next!=null)  
         heap.add(tmp.next);  
     }  
     return dummy.next;  
   }  
 }  


Sunday, January 4, 2015

Merge Two Sorted Lists (LeetCode Linked List)

Question: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Idea: The idea is quite intuitive. First initial a dummy head. Then compare the heads of l1 and l2 and drag the smaller of the two from the list, push the head pointing to the "victim" forward.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode mergeTwoLists(ListNode l1, ListNode l2) {  
     ListNode dummy=new ListNode(0);  
     ListNode cur=dummy;  
     while(l1!=null&&l2!=null)  
     {  
       int v1=l1.val;  
       int v2=l2.val;  
       if(v1<=v2)  
       {  
         cur.next=l1;  
         l1=l1.next;  
       }  
       else  
       {  
         cur.next=l2;  
         l2=l2.next;  
       }  
       cur=cur.next;  
     }  
     if(l1!=null)  
       cur.next=l1;  
     if(l2!=null)  
       cur.next=l2;  
     return dummy.next;  
   }  
 }  

Linked List Cycle II (LeetCode Linked List)

Question: Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?

Idea: As we know, the faster pointer will catch up the slower pointer if there is a cycle. The solution is an extension of this idea. Since the explanation needs a little math, let us first set the following notations to make it easier to be understood.

x: the length of the non-cycle part.
r: the length of the cyclic part.
a: the distance from the cycle entry to the point faster meets slower.
s: the distance the slower has traversed.
n: the number of runs the faster has traversed the whole cycle when faster meets slower.

When faster meets slower, the faster (slower) has traversed 2s (s), which can be represented as:
                          2s=x+nr+a
                            s=x+a
so we have          s= nr
and                      nr=x+a -> x=nr-a

As we know the slower is at position a when faster and slower meet, if the slower goes forward nr-a steps, the slower will reach the entry of the cycle. Since x=nr-a, if we let another pointer slower2 start from the head and run x steps with speed 1 step/run. It will meet the slower at the entry of the cycle.

Therefore the algorithm is like this:
1) Let faster and slower meet.
2) Start another pointer slower2 from head.
3) Let slower and slower2 both run 1step/time.
4) slower and slower2 must meet at the entry of the cycle. Return the entry pointer.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode detectCycle(ListNode head) {  
     if(head==null||head.next==null)  
       return null;  
     ListNode faster=head;  
     ListNode slower=head;  
     while(faster!=null&&faster.next!=null)  
     {  
       faster=faster.next.next;  
       slower=slower.next;  
       if(slower==faster)  
       {  
         ListNode slower2=head;  
         while(slower!=slower2)  
         {  
           slower=slower.next;  
           slower2=slower2.next;  
         }  
         return slower;  
       }  
     }  
     return null;  
   }  
 }  

Linked List Cycle (LeetCode Linked List)

Question: Given a linked list, determine if it has a cycle in it.

Idea: Like the minute hand will always catch up the hour hand on the clock, a faster running pointer will always catch up the slower running pointer if there is a cycle in the linked list. This is a classic math problem and it has many applications, e.g. blind channel hopping.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public boolean hasCycle(ListNode head) {  
     if(head==null||head.next==null)  
       return false;  
     ListNode slower=head;  
     ListNode faster=head;  
     while(faster.next!=null)  
     {  
       faster=faster.next;  
       if(faster==slower)  
         return true;  
       slower=slower.next;  
       faster=faster.next;  
       if(faster==null)  
         return false;  
     }  
     return false;  
   }  
 }  

Intersection of Two Linked Lists (LeetCode Linked List)

Question:  Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:

A:          a1 → a2
                           ↘
                                 c1 → c2 → c3
                              ↗          
B:     b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

Idea:  Assume the length of A and B can be denoted as
aTotal= unmatchedA+commonC
bTotal=unmatchedB+commonC.
Then aTotal-bTotal=unmatchedA-unmatchedB. Without loss of generality, let us assume is longer. Then can know the unmatched part of A is aTotal-bTotal longer than the unmatched part B. Therefore we just need to skip the first aTotal-bTotal nodes in A to make A and B aligned. Then we traversal A and B simultaneously until they meet. If they did not meet before reaching null, return null.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode getIntersectionNode(ListNode headA, ListNode headB) {  
     int lenA=getLength(headA);  
     int lenB=getLength(headB);  
     if(lenA>lenB)  
     {  
       for(int i=0;i<lenA-lenB;i++)  
         headA=headA.next;  
     }  
     if(lenA<lenB)  
     {  
       for(int i=0;i<lenB-lenA;i++)  
         headB=headB.next;  
     }  
     while(headA!=null&&headB!=null)  
     {  
       if(headA==headB)  
         return headA;  
       headA=headA.next;  
       headB=headB.next;  
     }  
     return null;  
   }  
   public int getLength(ListNode head)  
   {  
     int counter=0;  
     while(head!=null)  
     {  
       counter+=1;  
       head=head.next;  
     }  
     return counter;  
   }  
 }  

Insertion Sort List (LeetCode Linked List)

Question: Sort a linked list using insertion sort.

Idea: Create a constant dummy head. Then traversal the linked list. Whenever a node, say node i, is visited, initial a pointer to start from the dummy head and find the position to insert the node i.  After finishing the traversal, the sort is done. Return the dummy head's next node.

Time: O(n^2)  Space: O(1)

Code:
 public class Solution {  
   public ListNode insertionSortList(ListNode head) {  
     ListNode dummy=new ListNode(Integer.MIN_VALUE);  
     while(head!=null)  
     {  
       ListNode tmp=dummy;  
       while(tmp.next!=null&&tmp.next.val<head.val)  
         tmp=tmp.next;  
       ListNode nextNode=head.next;  
       head.next=tmp.next;  
       tmp.next=head;  
       head=nextNode;  
     }  
     return dummy.next;  
   }  
 }  


Convert Sorted List to Binary Search Tree (LeetCode Linked List)

Question: Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

Idea: This idea comes from tree in order traversal. The in order traversal of the tree is the same as scanning the linked list from head to tail. So we first calculate the length of the linked list, assume it is denoted as n. Then we construct a BST with size n but with all values 0. Finally we in order traversal the BST and scan the linked list simultaneously and assign the corresponding value to the tree node. The only trick is their sequences are completely the same.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   ListNode cur;  
   public TreeNode sortedListToBST(ListNode head) {  
     cur=head;  
     return generate(getLength(head));  
   }  
   public TreeNode generate(int n)  
   {  
     if(n==0)  
       return null;  
     TreeNode node=new TreeNode(0);  
     node.left=generate(n/2);  
     node.val=cur.val;  
     cur=cur.next;  
     node.right=generate(n-n/2-1);  
     return node;  
   }  
   public int getLength(ListNode head)  
   {  
     int counter=0;  
     while(head!=null)  
     {  
       counter+=1;  
       head=head.next;  
     }  
     return counter;  
   }  
 }  

Add Two Numbers (LeetCode Linked List)

Question: You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Idea: Brute force. Keep adding if l1 or l2 is not empty or the carry is not 0. Keep a pointer pointing consistently to the head of the intended results, otherwise it is impossible to find the head of the result when the result is going to be returned : (

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public ListNode addTwoNumbers(ListNode l1, ListNode l2) {  
     ListNode dummy=new ListNode(-1);  
     ListNode cur=dummy;  
     int carry=0;  
     while(l1!=null||l2!=null||carry!=0)  
     {  
       int valOne=0;  
       int valTwo=0;  
       if(l1!=null)  
       {  
         valOne=l1.val;  
         l1=l1.next;  
       }  
       if(l2!=null)  
       {  
         valTwo=l2.val;  
         l2=l2.next;  
       }  
       int sum=valOne+valTwo+carry;  
       carry=sum/10;  
       sum=sum%10;  
       cur.next=new ListNode(sum);  
       cur=cur.next;  
     }  
     return dummy.next;  
   }  
 }