LeetCode OJ 61. Rotate List

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可能大于链表的长度。此时要旋转的长度就是k%list.length。

解决这个问题我分为了两个步骤:

  1. 求链表的长度;
  2. 进行旋转操作;
 1 public class Solution {
 2     public ListNode rotateRight(ListNode head, int k) {
 3         if(k<0 || head==null) return null;
 4         
 5         int length = 0;
 6         ListNode temp = head;
 7         ListNode temp2 = head;
 8         while(temp!=null){
 9             temp = temp.next;
10             length++;
11         }
12         k = k%length;
13         temp = head;
14         
15         while(temp.next != null){
16             if(k<1) temp2 = temp2.next;
17             temp = temp.next;
18             k--;
19         }
20         temp.next = head;
21         head = temp2.next;
22         temp2.next = null;
23         return head;
24     }
25 }

参考了别人的代码,找到了更加简便的方法,这个方法只用到了一个指针,很值得我们学习。

 1 public ListNode rotateRight(ListNode head, int k) {
 2     if(head == null || k == 0) {
 3         return head;
 4     }
 5     ListNode p = head;
 6     int len = 1;
 7     while(p.next != null) {
 8         p = p.next;
 9         len++;
10     }
11     p.next = head;
12     k %= len;
13     for(int i = 0; i < len - k; i++) {
14         p = p.next;
15     }
16     head = p.next;
17     p.next = null;
18     return head;
19 }
原文地址:https://www.cnblogs.com/liujinhong/p/5394686.html