[LeetCode][Java] Rotate List

2015-07-20 17:06:09 ? 作者: ? 浏览: 2

题目:

?

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.

?

题意:

给定一个链表,以距离右边界k点的节点为轴,旋转这个链表,k为非负数。

比如:

Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

?

算法分析:

* 给出一个单链表,和一个K值,根据K值往右旋转,例如:
* 注意审题 ,开始以为K点从左边开始呢,debug费了那么大劲~~

* K是从右向左数的

*还需要特别说明的一点是,k的值可能会超过链表中的节点数,这时候需要对k进行取余操作,重新定位k在链表中的位置。当k取余数0时,说明为总节点数的

*整数倍,这时候依照题意链表不需要进行翻转。
* [1,2,3,4,5] k=1 ----->[5,1,2,3,4]
* [1,2,3,4,5] k=2 ----->[4,5,1,2,3]
* [1,2,3,4,5] k=3 ----->[3,4,5,1,2]
* [1,2,3,4,5] k=4 ----->[2,3,4,5,1]

?

参考http://pisxw.com/algorithm/Rotate-List.html

?

此题解法依旧是利用双指针,基本思路是设置两个指针i,j,中间相差n,用walker-runner定位到要旋转的那个结点,然后将下一个结点设为新表头,并且把当前结点设为表尾。设置前后两个指针,然后推进前进的方法称为尺取法。

?

AC代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution 
{
    public ListNode rotateRight(ListNode head, int n) 
    {
        if(head==null || head.next==null)
            return head;
        ListNode slow=head;      //定义两个指针
        ListNode fast=head;
        ListNode testhead =head;//复制链表,用于后面统计链表中的总的节点数
        int Nodenum=0;         //链表中的节点数
        int k;
    	while(testhead!=null)
     	{
     		Nodenum++;         //统计总共多少节点
     		testhead=testhead.next;
     	}
     	k=n%Nodenum;
     	if(k==0)              //若n正好为节点数的整数倍,就不用翻转链表
     	  return head;
        for(int num=0;num
   

?

自己第一遍的AC代码,真叫一个乱啊,舍不得还是记录下吧

public class Solution 
{
    public ListNode rotateRight(ListNode head, int k) 
    {
		//1->2->3->4->5->NULL
    	//4->5->1->2->3->NULL.
    	int Nodenum=0;
    	ListNode testhead2;
    	ListNode testhead3;
    	ListNode newListone;
    	ListNode newListtwo;
      	ListNode Listtwoend;
    	
    	if(head==null||head.next==null) 
    		return head;
    	ListNode testhead =head;
    	
    	while(testhead!=null)
    	{
    		Nodenum++;
    		testhead=testhead.next;
    	}
    	k=k%Nodenum;
    	if(k>=Nodenum||k==0)
    		return head;
    	testhead2=head;
    	testhead3=head;
   
    	for(int i=1;i
   



?

-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: