Leetcode 61. Rotate List

来源:互联网 发布:excel比对重复数据 编辑:程序博客网 时间:2024/05/18 03:33

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.

s思路:
1. 没什么好说的。需要理解题意,由于往右shift k个位置,k很可能超过List长度。自己做,会默认k

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ //方法1:pointer-to-pointerclass Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if(!head)  return NULL;        ListNode** p=&head,*fast=head;        int len=0;        while(fast){            fast=fast->next;            len++;        }        int pos=k%len;        if(pos==0) return head;        fast=head;        while(--pos){            fast=fast->next;        }        while(fast->next){            fast=fast->next;            p=&((*p)->next);        }        fast->next=head;        head=(*p);        *p=NULL;        return head;    }};//方法2:简单做法。先扫一遍找到长度,然后把尾巴和开头连起来;//再扫描找到需要改变头节点的位置,因此就不用pointer-to-pointer这些复杂的技能了,因为头节点位置可确定!class Solution {public:    ListNode* rotateRight(ListNode* head, int k) {        if(!head)  return NULL;        ListNode* newhead=NULL,*tail=head;        int len=1;        while(tail->next){            tail=tail->next;            len++;        }        tail->next=head;        if(k%=len){            for(int i=0;i<len-k;i++)                tail=tail->next;        }        newhead=tail->next;        tail->next=NULL;        return newhead;    }};
0 0