您的位置:首页 > 编程语言 > Python开发

61. Rotate List

2018-03-15 10:54 120 查看
题目描述:Given a list, rotate the list to the right by k places, where k is non-negative.

Example:Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.我的思路:给定一个链表(有对应的类),以右边第k个元素为界,前后调换。先找到倒数第k+1个位置,指向末尾;再把末尾的元素指向链表头。
我的代码:# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def rotateRight(self, head, k):
if head == None or head.next == None or k == 0: # 空链表,只有一个节点,或者位置在尾部,直接返回head
return head
i = 0
p = head
while p:                                           # 这层循环是为了求整个链表长度
i += 1
p = p.next
p = head # p,q一个在前,一个在后
q = head
k = k % i                                          # 这步是为了,处理k大于整个链表长度的时候
while k > 0:                                       # 这个循环是为了让q领先p k步
q = q.next
k -= 1
while q.next:                                      # p,q同步向后查找
p = p.next
q = q.next
q.next = head
newhead = p.next
p.next = None
return newheadDiscuss:ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL || head->next == NULL || k == 0) return head;
int len = 1;
ListNode *tail = head;

/* find the end of list */
while (tail->next != NULL) {
tail = tail->next;
len++;
}

/* form a circle */
tail->next = head;
k = k % len;
for (int i = 0; i < len - k; i++) {
tail = tail->next;
}
head = tail->next;
tail->next = NULL;
return head;
}学到:

Discuss中找到p,q以后,链表的操作要简单一点。这道题卡在了各种边界条件了,思路没有问题。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python leetcode