Monday, April 23, 2012

Linked List Rotation

[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.

[Analysis]
Just need to be careful that the k could be larger than the length of the linked list.

[Solution]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head==null) return null;
     
        ListNode p = head;
        int count=0;
        while (p.next!=null) {
            count++;
            p=p.next;
        }
        count++;
        p.next = head;
     
        n = n % count;
     
        p=head;
        while (n+1<count) {
            n++;
            p=p.next;
        }
     
        head = p.next;
        p.next = null;
     
        return head;

    }

}

No comments:

Post a Comment