Fork me on GitHub

61.旋转链表

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
   public ListNode rotateRight(ListNode head, int k) {
		if(head == null)
			return null;
		ListNode flag = head;
		ListNode ls1  = head;
		ListNode ls2  = head;
		int len = 0;
		while(flag != null) {
			len++;
			flag = flag.next;
		}
		k = k % len ; 
		for(int i = 0 ; i < k ; i++) {
			ls1 = ls1.next;
		}
		while(ls1.next!=null) {
			ls1 = ls1.next;
			ls2 = ls2.next;
		}
		ls1.next = head;
		ListNode ls3  = ls2.next;
		ls2.next = null;
		
		return ls3;
	}
}
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null) return null;
        ListNode work = head;
        int count = 0;
        while (work != null) {
            count++;
            work = work.next;
        }
        k = k % count;
        if (k == 0) {
            return head;
        }
        work = head;
        ListNode pre = head;
        for (int i = 0; i < count - k; i++) {
            pre = work;
            work = work.next;
        }
        pre.next = null;
        pre = head;
        head = work;
        while (work.next != null) {
            work = work.next;
        }
        work.next = pre;
        return head;
    }
}
posted @ 2019-07-24 10:03  cznczai  阅读(90)  评论(0编辑  收藏  举报