题解 | #链表内指定区间反转#
链表内指定区间反转
https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
if(m==n){
return head;
}
// else
struct ListNode* p;
p = head;
int count = 1;
while(p->next!=NULL && count<m){
p = p->next;
count++;
}
struct ListNode* p1;
p1 = head;
if(m!=1){
while(p1->next!=p){
p1 = p1->next;
}
}
// p停在m位置
// printf("p->val: %d\n",p->val);
struct ListNode* q;
q = p;
while(q->next!=NULL && count<n){
q = q->next;
count++;
}
// q停在n当前的位置
// printf("q->val: %d\n",q->val);
// sub
struct ListNode* subp;
subp = NULL;
struct ListNode* subtail;
struct ListNode* headp;
headp = p;
struct ListNode* temp;
int flag = 0;
while(headp != q->next){
temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp -> next = NULL;
temp -> val = headp -> val;
temp -> next = subp;
if(flag == 0){
temp -> next = q->next;
}
subp = temp;
headp = headp -> next;
flag++;
}
// output the sub list
// printf("the sub list \n");
// struct ListNode* psub;
// psub = subp;
// while(psub!=NULL){
// printf("%d ", psub->val);
// psub = psub->next;
// }
// printf("\n");
if(m!=1){
p1->next = temp;
return head;
}else{
// p1 = temp;
return temp;
}
}
联想公司福利 1477人发布