[Leetcode61] 旋转链表

给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。

这道题不难,就是不知道为什么运行时间比较慢。

python:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def rotateRight(self, head, k):
        """
        :type head: ListNode
        :type k: int
        :rtype: ListNode
        """
        if head == None:
            return None
        if head.next == None:
            return head
        test = ListNode(0)
        test.next = head
        length = 0
        while test.next:
            length += 1
            test = test.next
        for i in range(k % length):
            original = head
            while original.next.next:
                original = original.next
            temp = ListNode(original.next.val)
            original.next = None
            temp.next = head
            head = temp
        return head

C++: 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* rotateRight(ListNode* head, int k) {
        if(head == NULL) return NULL;
        if(head->next == NULL) return head;
        int len = 0;
        ListNode* temp = new ListNode(0);
        temp->next = head;
        while(temp->next){
            temp = temp->next;
            len += 1;
        }
        for(int i = 0;i < (k % len);i++){
            ListNode* original = head;
            while((original->next)->next){
                original = original->next;
            }
            ListNode* start = new ListNode((original->next)->val);
            original->next = NULL;
            start->next = head;
            head = start;
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_40501689/article/details/83030467