leetcode--61--旋转链表

题目描述:

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

示例 1 :
输入: 1->2->3->4->5->NULL, k = 2
输出: 4->5->1->2->3->NULL
解释:
向右旋转 1 步: 5->1->2->3->4->NULL
向右旋转 2 步: 4->5->1->2->3->NULL

示例 2 :
输入: 0->1->2->NULL, k = 4
输出: 2->0->1->NULL
解释:
向右旋转 1 步: 2->0->1->NULL
向右旋转 2 步: 1->2->0->NULL
向右旋转 3 步: 0->1->2->NULL
向右旋转 4 步: 2->0->1->NULL


解题思路1:

当链表在向右移动时, 移动的步数k有可能大于链表的长度。 移动链表后会让原链表的头和尾首尾相接,这就相当于是找一个环形链表的断开点, 找到这个新链表的头节点。因此,

  1. 将原链表尾节点指向头节点, 将原链表改造成一个环形链表.
  2. 根据移动步数k计算链表的断开点.
  3. 将断开的节点做头结点, 同时把新的尾节点置空.

代码:

python

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 not head:
            return head
        if k==0:
            return head

        ori_head = head
        n = 1
        while head.next:
            head = head.next
            n += 1
        head.next = ori_head  #  将列表前后连上
        move_num = n - k % n -1
        while move_num > 0:
            ori_head = ori_head.next
            move_num -= 1
        new_head = ori_head.next
        ori_head.next = None  # 将列表断开

        return new_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 (not head){
            return head;
        }
        if (k==0){
            return head;
        }
        ListNode* ori_head = head;
        int n=1;
        while (head->next!=NULL){
            head = head->next;
            n += 1;
        }
        head->next = ori_head;
        int move_num = n - k%n -1;
        while(move_num>0){
            ori_head = ori_head->next;
            move_num -= 1;
        }
        ListNode* new_head = ori_head->next;
        ori_head->next = NULL;
        return new_head;
    }
};

参考链接:

[1]. [LeetCode]61. 旋转链表
[2]. leetcode–61–旋转链表

题目来源: https://leetcode-cn.com/problems/rotate-list

发布了333 篇原创文章 · 获赞 36 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/104648379
今日推荐