LeetCode.61 Rotate List

来源:互联网 发布:python与 shell 编辑:程序博客网 时间:2024/06/05 00:31
题目:

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.

分析1(实测较分析2快,易理解):
/** * 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) {        //给定链表,对调末尾k个节点        //求出链表长度        //需要考虑k大于链表长度的情况,例如:输入【1,2】3 输出【2,1】,输入【1,2】 4 输出【1,2】        int len=listLength(head);        if(head==null||k<=0)return head;                //考虑k大于链表节点大的情况        k=k%len;                //链表长度减去k则为前半部分        ListNode dummy=new ListNode(0);        ListNode res=dummy;        dummy.next=head;        ListNode cur=head,pre=dummy;                for(int i=len-k;i>0;i--){            pre=pre.next;            cur=cur.next;        }                //调换后半部k个节点        while(cur!=null){            pre.next=cur.next;            cur.next=dummy.next;            dummy.next=cur;            dummy=dummy.next;            cur=pre.next;        }                return res.next;        }    public int listLength(ListNode head){        ListNode pre=head;        int count=0;        while(pre!=null){            count++;            pre=pre.next;        }        return count;    }}
分析2:

/** * 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) {        //首先要看k是否大于链表的长度,若是大于长度,则对其求余k%len的位置旋转        //最后next指向head,形成一个环,之后遍历新的head的前一个节点的next赋值null,最后返回head        if(head==null||k<0)return head;        int count=1;        ListNode cur=head;        while(cur.next!=null){            count++;            cur=cur.next;        }                //获取右边开始节点的下标        k=k%count;                //将最后一个节点next指向head,形成环        cur.next=head;                //接下来遍历节点数        int num=count-k;        for(int i=0;i<num;i++){            cur=cur.next;        }                head=cur.next;        //断链        cur.next=null;        return head;    }}



原创粉丝点击