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
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- rotate-list
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- Rotate List
- 使用data()方法在元素上存取移除JSON格式数据 10-6
- 各自了解浏览器本质的一部分
- Openfire资料汇总
- linux基础----vi三种模式
- 内存分配:new的三种方法-new expression、operator new和placement new
- Rotate List
- ACM 93. [NOIP2001] 数的划分(dp+组合数学)
- Shell 常识--正则表达式,POSIX字符类以及元字符--总结自《Linux Shell 脚本攻略》
- Mac环境下svn的使用
- 孤儿进程与僵尸进程
- 基于左右值的无限分类算法
- iOS 常用数学函数
- C语言scanf函数详细解释
- 一切成功源于积累——20140902 市场洞察一切人性 Nothing learned, and everything forgotten-2