【leetcode】Reverse Linked List I & II
2015-05-05 15:02
232 查看
Reverse a singly linked list.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
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.
click to show more hints.
Hint:
A linked list can be reversed either iteratively or recursively. Could you implement both?
class Solution { public: ListNode* reverseList(ListNode* head) { if(head==NULL||head->next==NULL) return head; ListNode *p=head->next; ListNode *newhead=reverseList(head->next); head->next=NULL; p->next=head; return newhead; } };
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.
class Solution { public: ListNode* reverseBetween(ListNode* head, int m, int n) { if(head==NULL||m<0||n<0) return head; if(head->next==NULL||m==n) return head; ListNode *p=head; int i=1; while(i<m) { p=p->next; i++; } for(int j=m;j<n;j++) { ListNode *q=p; for(int k=j;k<n;k++) { q=q->next; } swap(p->val,q->val); n--; p=p->next; } return head; } };
相关文章推荐
- LeetCode解题报告—— Linked List Cycle II & Reverse Words in a String & Fraction to Recurring Decimal
- leetcode 25. Reverse Nodes in k-Group & leetcode 92. Reverse Linked List II
- LeetCode 206. Reverse Linked List && 92. Reverse Linked List II
- LeetCode之“链表”:Reverse Linked List && Reverse Linked List II
- [Leetcode] #92#206 Reverse Linked List I & II
- [LeetCode]206. Reverse Linked List&92. Reverse Linked List II
- 【Leetcode】92. Reverse Linked List II && 206. Reverse Linked List
- LeetCode解题报告—— Reverse Linked List II & Restore IP Addresses & Unique Binary Search Trees II
- LeetCode-Reverse Linked List II
- leetcode-Reverse Linked List II-92
- leetcode92. Reverse Linked List II
- LeetCode Reverse Linked List II
- Leetcode: 92. Reverse Linked List II
- leetcode-92. Reverse Linked List II(将单链表部分进行转置)
- LeetCode92 Reverse Linked List II
- [leetcode] Reverse Linked List II
- LeetCode | Reverse Linked List II(翻转链表2)
- LeetCode - Reverse Linked List II
- [LeetCode] Reverse Linked List II
- [Leetcode 73] 92 Reverse Linked List II