程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode] 61 Rotate List,leetcoderotate

[LeetCode] 61 Rotate List,leetcoderotate

編輯:C++入門知識

[LeetCode] 61 Rotate List,leetcoderotate


   

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

For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

解題思路:

雙指針(tail,pre)找到鏈表的尾部和總長度,使用pre走 (len-k%(len)-1) 長度到達要修改的尾部點進行修改

/**
 * 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)return head;
        ListNode *tail,*pre;
        tail=pre=head;
        int len=1;
        while(tail->next!=NULL) //找到尾部
        {
            tail=tail->next;
            len++;
        }
        int i=len-(k%(len))-1;  //考慮k數據的過大
        while(i>0)
        {
            i--;
            pre=pre->next;
        }
        tail->next=head;
        head=pre->next;
        pre->next=NULL;
        return head;
    }
};

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved