p127 旋转单链表(leetcode 61)
一:解题思路
一:这个题目是将链表右边的结点循环移动到链表的左边来。
1.将链表首位相连,移动次数为K,K=K%N (N为链表的长度)。
2.然后,再找新的链表的结束尾结点时,需要从链表头部走N-K-1步,即可以找到链表的新的尾部结点。
二:如果将这个题目改编一下,将链表左边的结点循环移动到链表的右边来,那该如何求解呢?
只需要在第一种题目的基础的2步骤中,从链表的头部走K-1步即可。
Time:O(n),Sapce:O(1)
二:完整代码示例 (C++版和Java版)
C++:
class Solution { public: ListNode* rotateRight(ListNode* head, int k) { if (head == NULL || head->next == NULL || k <= 0) return head; int n = 1; ListNode* end = head; for (; end->next != NULL; end = end->next) n++; end->next = head; k %= n; ListNode* newEnd = head; for (int i = 0; i < n - k - 1; i++) newEnd = newEnd->next; ListNode* newHead = newEnd->next; newEnd->next = NULL; return newHead; } };
Java:
class Solution { public ListNode rotateRight(ListNode head, int k) { if(head==null || head.next==null || k<=0) return head; int n=1; ListNode end=head; for(;end.next!=null;end=end.next) n++; end.next=head; k%=n; ListNode newEnd=head; for(int i=0;i<n-k-1;i++) newEnd=newEnd.next; ListNode newHead=newEnd.next; newEnd.next=null; return newHead; } }

浙公网安备 33010602011771号