Rotate List

来源:互联网 发布:php国外空间 编辑:程序博客网 时间:2024/05/17 01:09

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.

题目解析:

(1)一开始不知道链表的长度,所以对于旋转k个位置无法明确在哪个地方

(2)我们将链表遍历一次,得到他的长度,并将结尾指向链表头部形成循环链表

(3)k = k%index,用于处理k大于index的情况

(4)形成循环链表以后,我们在链表尾部,向前遍历(index-k)个位置。接着修改相应的指针就可以了。

(5)考虑的情况是,链表为空的时候应该返回什么。

#include <iostream>using namespace std;struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *rotateRight(ListNode *head, int k) {if(head == NULL)return head;int index = 1;ListNode *p = head;while(p->next != NULL){index++;p = p->next;}p->next = head;k = k%index;for(int m =(index - k);m>0;m--){p = p->next;}head = p->next;p->next = NULL;return head;}void printLinkedList(ListNode *head){while(head != NULL){cout << head->val << " ";head = head->next;}cout << endl;}int main(void){ListNode *head;ListNode *p;ListNode *temp = (ListNode *)malloc(sizeof(ListNode));temp->val = 1;head = temp;p=head;for(int i=2;i<=1;i++){temp = (ListNode *)malloc(sizeof(ListNode));temp->val = i;p->next = temp;p = temp;}p->next = NULL;head = NULL;printLinkedList(head);head = rotateRight(head, 6);printLinkedList(head);system("pause");return 0;}


0 0
原创粉丝点击