LeetCode
来源:互联网 发布:linux oracle 客户端 编辑:程序博客网 时间:2024/06/17 02:28
206. Reverse Linked List
Reverse a singly linked list.
时间复杂度O(n),空间复杂度O(1)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* reverseList(ListNode* head) { if (head == NULL || head->next == NULL) return head; ListNode* tail = NULL; ListNode* ans = NULL; while (head) { tail = head->next; head->next = ans; ans = head; head = tail; } return ans; }};
92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ? m ? n ? length of list.
反转部分链表,精髓还是反转链表。反转链表需要定义三个结点【敲黑板】,一个是答案,一个是当前结点,一个是前一个结点。时间复杂度O(n),空间复杂度O(n)
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public: ListNode* reverseBetween(ListNode* head, int m, int n) { if (!head) return head; ListNode node(0); ListNode* ans = &node; ans->next = head; for (int i = 0; i < m - 1; ++i) { ans = ans->next; } ListNode* pre = ans->next; for (int i = 0; i < n - m; ++i) { ListNode* cur = pre->next; pre->next = cur->next; cur->next = ans->next; ans->next = cur; } return node.next; }};
阅读全文
0 0
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode
- leetcode:
- leetcode:
- LeetCode
- leetcode
- LEETCODE
- leetcode
- leetCode
- leetcode
- [leetcode]
- LeetCode
- leetcode
- leetcode:
- leetcode
- Python 字典遍历
- 运算符
- java一维数组打印杨辉三角
- 欢迎使用CSDN-markdown编辑器
- HDOJ 1874 畅通工程续 (dijkstra算法)
- LeetCode
- 安装Web Storm
- c语言之函数(一)
- 个人总结TP框架小结
- 杭电1242
- bzoj3357[Usaco2004]等差数列 DP
- 这几天看的一篇文章很有感触的文章
- 【转】漫谈Moq(一)
- 关于函数的重载、覆盖和重写(Overload、Overwrite、Override)