Two pointers (1) -- Linked List Cycle II, Rotate List
来源:互联网 发布:重庆网络推广怎样 编辑:程序博客网 时间:2024/06/06 17:16
Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
ListNode *detectCycle(ListNode *head) { if (head == NULL) return NULL; ListNode* ptr = head; ListNode* fastPtr = ptr; do { if (fastPtr == NULL || fastPtr->next == NULL) return NULL; ptr = ptr -> next; fastPtr = fastPtr -> next -> next; } while (ptr != fastPtr); ptr = head; while (ptr != fastPtr){ ptr = ptr -> next; fastPtr = fastPtr -> next; } return ptr; }
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. 先找出list的长度,然后找到断开处的指针。
2. 使用快慢指针的话并不能减少指针移动的操作,所以不用了
ListNode* rotateRight(ListNode* head, int k) { if (head == NULL) return NULL; int len = 1; ListNode* ptr = head; while (ptr -> next != NULL){ ptr = ptr -> next; len++; } ListNode* tail = ptr; k = k % len; if (k == 0) return head; ptr = head; for (int i = 1; i < len - k; i++){ ptr = ptr -> next; } ListNode* newH = ptr -> next; ptr -> next = NULL; tail -> next = head; return newH; }
0 0
- Two pointers (1) -- Linked List Cycle II, Rotate List
- [leetcode][list][two pointers] Linked List Cycle II
- [leetcode][list][two pointers] Linked List Cycle
- [leetcode][list][two pointers] Reverse Linked List II
- Linked List Cycle II Linked List Cycle
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 约瑟夫问题
- Masonry介绍与使用实践:快速上手Autolayout
- AngularJS实际项目应用——命名规范概览
- SDWebImage 源码阅读(二)
- 位操作方法
- Two pointers (1) -- Linked List Cycle II, Rotate List
- linux 文件属性与权限(简单讲解)
- tomcat 启动失败
- button按钮onclick调用的函数名和id相同会导致找不到函数
- Mybatis框架原理
- schedule_work 工作队列
- C++幼儿园[2] - 数据类型和基本语法
- linux下查看文件内容工具发布啦!
- Android 简单的自定义控件(一)之BaseTitle