LeetCode刷题笔录 Rotate List

来源:互联网 发布:百度地图js touchend 编辑:程序博客网 时间:2024/06/05 00:10

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.

这题想法就是用两个pointer,一个比另外一个领先k个位置。对于上面那个例子,初始p1=1,p2=3;结束时p1=3,p2=5。

先扫描一遍链表,得到链表的长度,然后用k = n % length得到实际需要rotate的长度。

特殊情况:

1.list是空的

2.k=0

public class Solution {    public ListNode rotateRight(ListNode head, int n) {        if(head == null)            return null;        //get the length of the list        ListNode p1 = head;        int length = 1;        while(p1.next != null){            length++;            p1 = p1.next;        }        //get the rounded amount to rotate        int k = n % length;        //if k is zero, return as is        if(k == 0)            return head;        //use two pointers with k distance        p1 = head;        ListNode p2 = head;        for(int i = 0; i < k; i++){            p2 = p2.next;        }        while(p2.next != null){            p1 = p1.next;            p2 = p2.next;        }//the new head pointer is p1.next        p2 = head;        ListNode newHead = p1.next;        p1.next = null;        ListNode p3 = newHead;        while(p3.next != null){            p3 = p3.next;        }        p3.next = p2;                return newHead;    }}


可以优化一下:

第一遍跑到尾巴得到长度以后,直接p2.next = head,把尾巴和头连起来,然后再跑length - k长度,把next设置成null即可。这样少了一次扫描,也不用考虑k=0的情况了。

0 0
原创粉丝点击