LeetCode OJ:Reverse Linked List II(反转链表II)

时间:2021-11-03 05:54:21

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->NULLm = 2 and n = 4,

return 1->4->3->2->5->NULL.

Note:
Given mn satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.

大清早起来就被链表虐哭了啊, 看了下别人的,额原来可以这么简单,果然脑子还是转不过来的,实际上是很常见的一个题目,代码很简单,完全不用注释也可以的:

 /**
* 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 == NULL) return NULL;
ListNode * p = head;
int i, j;
for(i = ; i < m; ++i){
p = p->next;
}
ListNode * q = p;
for(i = m; i < n; ++i){
for(j = i; j < n; ++j){
q = q->next;
}
swap(p->val, q->val);
n--;
p = p->next;
q = p;
}
return head;
}
};

注意一下那个swap, swap用的很巧妙。

之后有看到一个大神写出来的,也很简单,贴出来学习一个:

 /**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL)
return NULL; ListNode *q = NULL;
ListNode *p = head;
for(int i = ; i < m - ; i++)
{
q = p;
p = p->next;
} ListNode *end = p;
ListNode *pPre = p;
p = p->next;
for(int i = m + ; i <= n; i++)
{
ListNode *pNext = p->next; p->next = pPre;
pPre = p;
p = pNext;
} end->next = p;
if (q)
q->next = pPre;
else
head = pPre; return head;
}
};

唉唉,经常遇到链表脑子就转不过来,这个还是要多练练啊。

下面贴一个java版本的,方法基本上和第一种差不多,熟悉一下用法:

 /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode reverseBetween(ListNode head, int m, int n) {
int count = 1;
ListNode helper = new ListNode(-1);
helper.next = head;
ListNode p = helper.next;
ListNode pPre = helper;
while(count != m){
p = p.next;
pPre = pPre.next;
count++;
}
ListNode midPre = pPre;//第一个节点的位置
ListNode tmp = null;
while(count != n){
tmp = p.next;
p.next = pPre;
pPre = p;
p = tmp;
count++;
}
// ListNode mid2= p; // 指向第二个节点的位置
tmp = p.next;
p.next = pPre;
midPre.next.next = tmp;
midPre.next = p;
return helper.next;
}
}