LeetCode[Linked list]: Rotate List
Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given1->2->3->4->5->NULLandk = 2,
return4->5->1->2->3->NULL.
看到这个题目感到奇怪的是为什么是“右旋”。而不是“左旋”呢?那么。左旋与右旋有什么差别呢?首先说一下我的解题思路:
首先把链表的头和尾连接起来成为一个环,然后通过指针的移动来实现旋转。旋转到正确的位置之后,将环断开成链表再返回。
依照这个思路,“左旋”确实要简单非常多,由于该链表是单向链表,而不是双向链表。
左旋代码实现例如以下:
ListNode *rotateLeft(ListNode *head, int k) {
if (!head) return NULL;
ListNode *curr = head;
while (curr->next) curr = curr->next; // 该循环找到尾节点
curr->next = head; // 此时curr指向尾节点,将尾连接至头
for (int i = 0; i < k; ++i)
curr = curr->next; // 左旋k步
head = curr->next; // 将环断开成为链表
curr->next = NULL;
return head;
}
那么假设依照这样的思路来实现右旋呢?一种投机取巧的方法就是右旋k步事实上就是左旋count
- k % count(count是指整个链表的长度)。代码实现例如以下:
ListNode *rotateRight(ListNode *head, int k) {
if (!head) return head;
if (k ==0) return head;
int count = 1;
ListNode *curr;
for (curr = head; curr->next != NULL; curr = curr->next)
++count;
curr->next = head;
for (int i = 0; i < count - k % count; ++i)
curr = curr->next;
head = curr->next;
curr->next = NULL;
return head;
}上面算法的时间复杂度均为O(N),空间复杂度为O(1),能够採取一定的手段牺牲空间性能去掉第二个循环来换取一定的时间性能:
ListNode *rotateRight(ListNode *head, int k) {
if (!head ) return head;
if (k == 0) return head;
vector<ListNode *> nodeVec;
for (ListNode *curr = head; curr != NULL; curr = curr->next)
nodeVec.push_back(curr);
int listLen = nodeVec.size();
k %= listLen;
if (k == 0) return head;
nodeVec[listLen - 1]->next = nodeVec[0];
nodeVec[listLen - k - 1]->next = NULL;
return nodeVec[listLen - k];
}不管是左旋还是右旋,均可通过上面的方式来实现。
空间复杂度变为O(N)。时间复杂度仍为O(N)。
以上是我独立思考的结果。看到Discuss上讨论比較多的是设置两个指针的做法。依照这个思路,我做了例如以下实现:

浙公网安备 33010602011771号