题解 | 链表内指定区间反转
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
#include <stdlib.h>
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
// write code here
if(m>=n || head==NULL || head->next==NULL)
return head;
// (1)定位反转区间
// 定义一个虚拟节点,应对m=1时
struct ListNode* dummy = (struct ListNode*)malloc(sizeof(struct ListNode));
dummy->next=head;
// 定位反转区间的头节点的前驱节点
struct ListNode* tou=dummy,* wei=dummy;
for(int i=0; i<m-1; i++){
tou=tou->next;
}
// 反转区间的尾结点
for(int i=0; i<n; i++){
wei=wei->next;
}
// (2)反转
struct ListNode* q, *p=tou->next;
tou->next = wei->next;
for(int i=0; i<n-m+1; i++){
q=p;
p=p->next;
q->next=tou->next;
tou->next=q;
}
return dummy->next;
}
伪代码:
/*
head->next = NULL
每次将q = p
将q插入head之后所有其它点之前
备注:这是头部不存值的时候
*/
int Reversehead() {
LinkList* q, * P = head->next;
head->next = NULL;
while (P) {
q = P;
P = P->next;
q->next = head->next;
head->next = q;
}
return 0;
}
#保研机试#