1.题目:
反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
2.代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/*
用头插法遍历链表同时将结点插到前面
*/
typedef struct ListNode* list;
struct ListNode* reverseBetween(struct ListNode* head, int m, int n){
list rhead=(list )malloc(sizeof(struct ListNode));
rhead->next=head;
list thead=rhead;
for(int i=1;i<m;i++)
thead=thead->next;
list pre=thead->next;
for(int i=m;i<n;i++){
list t=pre->next->next;
pre->next->next=thead->next;
thead->next=pre->next;
pre->next=t;
}
return rhead->next;
}
3.知识点:
头插法