leetcode_61_Rotate List

来源:互联网 发布:消防海湾主机编程实例 编辑:程序博客网 时间:2024/05/12 17:21

描述:

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.

思路:

本文的题意就是循环将后面的n个结点移动到前面去,所以,n有可能是大于链表的长度的,这是一个小小的陷阱。然后就是很简单的细节了,有点脑残,提交了好多次。

代码:

public ListNode rotateRight(ListNode head, int n) {        if(n<=0||head==null)        return head;        int len=1,index=0;        ListNode pListNode=head,qListNode=null,tailListNode=null;        while(pListNode.next!=null)        {        len++;            pListNode=pListNode.next;        }        tailListNode=pListNode;        n=n%len;        if(n==0)        return head;        index=len-n;        index--;        pListNode=head;        for(int i=0;i<index;i++)        {        pListNode=pListNode.next;        }        qListNode=pListNode.next;        pListNode.next=null;        pListNode=head;        head=qListNode;        tailListNode.next=pListNode;        return head;    }


结果:


0 0
原创粉丝点击