LeetCode---Rotate List
来源:互联网 发布:sql注入漏洞的危害 编辑:程序博客网 时间:2024/06/07 13:39
题目大意:给出一个链表,将其向右旋转k个节点。
算法思想:
1.如果链表为空或者K==0直接返回。
2.遍历链表,记录链表中的每个节点,并为其编号。
3.反向第K个节点将为表头结点,将尾节点和头结点连接起来。
4.如果K大于链表的长度 k%=list.size.
代码如下:
/** * 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||k==0) return head; ListNode* p=head; map<int,ListNode*> Node; int num=0; while(p){ Node.insert(make_pair(++num,p)); p=p->next; } if(k>=Node.size()) k=k%Node.size(); if(k==0) return head; ListNode *wzg=new ListNode(0); wzg->next=Node[Node.size()-k+1]; if(wzg->next==head){ delete wzg; return head;} Node[Node.size()]->next=Node[1]; Node[Node.size()-k]->next=NULL; head=wzg->next; delete wzg; return head; }};
0 0
- [leetcode][list] Rotate List
- LeetCode: Rotate List
- LeetCode Rotate List
- LeetCode : Rotate List
- [Leetcode] Rotate List
- [LeetCode] Rotate List
- [leetcode] Rotate List
- leetcode 70: Rotate List
- [Leetcode] Rotate List
- 【leetcode】Rotate List
- [LeetCode]Rotate List
- [leetcode]Rotate List
- LeetCode-Rotate List
- [leetcode] Rotate List
- LeetCode - Rotate List
- LeetCode:Rotate List
- LeetCode 61: Rotate List
- leetcode之Rotate List
- 25. Remove Element
- 关于在Ubuntu下安装Java
- hdu 1863(prim&kruskal)
- 基于皮尔森相关系数的协同过滤算法
- DIRECTORY_SEPARATOR
- LeetCode---Rotate List
- mysql 数据查询语句优化 null
- 我的OpenCV学习笔记(12):VideoCapture类
- 链表c++实现
- 最近的学习
- 图中节点的度数
- HTML学习笔记之框架的应用
- 使用!访问到具体的method中,而不是直接在xml中设置
- 奇虎360 android 安全卫士 root核签名认证分析