LeetCode-Rotate List

来源:互联网 发布:编程原本pdf 编辑:程序博客网 时间:2024/06/16 19:05
作者:disappearedgod
文章出处:http://blog.csdn.net/disappearedgod/article/details/24016491
时间:2014-4-22

题目

Rotate List

 Total Accepted: 8094 Total Submissions: 37399My Submissions

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.

 Definition for singly-linked list. public class ListNode {     int val;     ListNode next;     ListNode(int x) {         val = x;         next = null;     } } 

解法

思想:成循环节点,到循环位置解开
public ListNode rotateRight(ListNode head, int n) {        if(head==null)            return head;        ListNode loop = head;        ListNode end = head;        ListNode front = head;                while(loop.next!=null)            loop = loop.next;        loop.next=head;                end = loop;        loop = head;                for(int i = 0; i < n;i++){            loop = loop.next;        }        while(loop != end){            loop = loop.next;            front = front.next;        }        ListNode ret = front.next;        front.next = null;                return ret;            }



返回

LeetCode Solution(持续更新,java>c++)


0 0
原创粉丝点击