@snuffles
2019-04-10T10:35:52.000000Z
字数 853
阅读 850
链表
给定一个链表,旋转链表,将链表每个节点向右移动 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
解:先获得链表长度,把链表头尾链接起来,往后走N-K%N个节点,到达新头结点前的一个点,断开链表。
ListNode* rotateRight(ListNode* head, int k) {
if(!head) return NULL;
ListNode *cur = head;
int count=0;
while(cur->next){
count ++;
cur = cur->next;
}
count ++; //length
cur->next = head;//link the head and tail;
int move = count-k%count;
ListNode *newhead = head,*newtail = head;
while(move--){
newhead = newhead->next;
}
move = count-k%count-1;
while(move--){
newtail = newtail->next;
}
newtail->next = NULL;
return newhead;
}
ListNode* rotateRight(ListNode* head, int k) {
if(head ==NULL || k==0) return head;
ListNode *tail = head;
int len=1;
while(tail->next){
tail=tail->next;
len++;
}
tail->next = head;
ListNode *newhead = head;
int count=len-k%len;
while(count--){
newhead = newhead->next;
tail = tail->next;
}
tail->next = NULL;
return newhead;
}