题目描述:
92
Reverse a linked list from position m to n. Do it in one-pass.
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4 Output: 1->4->3->2->5->NULL
206
Example:
Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
算法实现:
这两个问题很是类似,206可以说是92的一个子问题,比较基础
/**
* 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) {
ListNode *L = head;
ListNode *p = NULL;
ListNode *pp;
while(L != NULL){
pp = L -> next;
L -> next = p;
p = L;
L = pp;
}
return p;
}
};
对于第92题,只需要找到要反转部分的第一个节点,反转部分前后的相邻节点,两种方法
- 一种是直接找到反转部分的后一节点,反转时直接将反转部分的头节点链接到这一节点
/**
* 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(m >= n)return head;
ListNode *suanz = new ListNode(0);
suanz -> next = head;
int i = 0;
//记录反转链表的第一个节点
ListNode *L;
//记录反转链表之前的第一个节点
ListNode *p = suanz;
//记录反转链表之后的第一个节点
ListNode *pe;
while(i < m - 1 && p != NULL){
p = p -> next;
i ++;
}
L = p -> next;
i ++;
pe = L;
while(i < n + 1 && pe != NULL){
pe = pe -> next;
i ++;
}
i = m;
ListNode *pp;
// cout << pe -> val << endl;
// cout << L -> val << endl;
while(i <= n){
pp = L -> next;
L -> next = pe;
pe = L;
L = pp;
i ++;
}
p -> next = pe;
return suanz -> next;
}
};
- 另一种是稍微进行了优化,不找到反转部分的后一节点,反转时先将反转部分的头节点指向反转部分的前一节点,反转过程完成后再修正这个地方,这样操作少搜索了依次反转部分
/**
* 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(m >= n)return head;
ListNode *suanz = new ListNode(0);
suanz -> next = head;
int i = 0;
//记录反转链表的第一个节点
ListNode *L,*Lp;
//记录反转链表之前的第一个节点
ListNode *p = suanz;
//记录反转链表之后的第一个节点
ListNode *pe;
while(i < m - 1 && p != NULL){
p = p -> next;
i ++;
}
L = p -> next;
i ++;
// pe = L;
// while(i < n + 1 && pe != NULL){
// pe = pe -> next;
// i ++;
// }
pe = p;
Lp = L;
i = m;
ListNode *pp;
// cout << pe -> val << endl;
// cout << L -> val << endl;
while(i <= n){
pp = L -> next;
L -> next = pe;
pe = L;
L = pp;
i ++;
}
p -> next = pe;
Lp -> next = pp;
return suanz -> next;
}
};