[leetcode] 61. Rotate List

61. Rotate List

Description

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL
Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL

Analysis

方法一就是简单粗暴地每次将最后一个元素插入到第一个元素,重点是要设一个fakeHead指针指向头结点之前的节点。
方法二是讲链表闭合成一个环,这样的话每次插入不用改变链表的顺序,只截取其中新的head和tail即可。
还有一个tips就是在计算插入次数k的时候,要取模k=k%(链表长度)。否则会time limit exceeded。

Code

方法一:设一个fakeHead指向head的前一个值(fakeHead->next = head)。每次插入的时候将链表最后一个值插到fakeHead->next,然后将倒数第二个值的next设为NULL。

/**
 * 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 || head->next==NULL || k==0)  return head;
        ListNode* fakeHead = new ListNode(0);
        fakeHead->next = head;
        
        ListNode* p = head;
        
        int length = 0;
        while(p){
            p = p->next;
            length++;
        }
        cout<<length<<endl;
        
        k = k%length;
        
        p = head;
        
        while(k>0){
            ListNode* pre = p;
            while(p->next){
                pre = p;
                p = p->next;
            }   
            p->next = fakeHead->next;
            fakeHead->next = p;
            pre->next = NULL;
            k--;
        }
        
        return fakeHead->next;
    }
};

方法二(SOLUTION: JAVA):
将链表闭合成一个环,让链表最后一个值tail->next = head。然后计算new_tail和new_head各是第几个元素,然后将new_tail前面那个元素的next设为NULL。最后返回new_head。

class Solution {
  public ListNode rotateRight(ListNode head, int k) {
    // base cases
    if (head == null) return null;
    if (head.next == null) return head;

    // close the linked list into the ring
    ListNode old_tail = head;
    int n;
    for(n = 1; old_tail.next != null; n++)
      old_tail = old_tail.next;
    old_tail.next = head;

    // find new tail : (n - k % n - 1)th node
    // and new head : (n - k % n)th node
    ListNode new_tail = head;
    for (int i = 0; i < n - k % n - 1; i++)
      new_tail = new_tail.next;
    ListNode new_head = new_tail.next;

    // break the ring
    new_tail.next = null;

    return new_head;
  }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值