反转从位置 m 到 n 的链表。请使用一趟扫描完成反转。
说明:
1 ≤ m ≤ n ≤ 链表长度。
示例:
输入: 1->2->3->4->5->NULL, m = 2, n = 4
输出: 1->4->3->2->5->NULL
通过次数115,960提交次数219,660
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/reverse-linked-list-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
第一种思路
重新申请链表空间
在给定区间使用头插法
在非给定区间使用尾插法
第二种思路
直接将给定区间使用头插法重新写一份链表a
然后将a直接插进原链表
第二种思路代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseBetween(struct ListNode* head, int left, int right){
//结合头插法,但最后一个的指针得留着
if(left==right) return head;
int count =1;
struct ListNode * last = head;
struct ListNode * cur = head;
struct ListNode * temp = (struct ListNode*)malloc(sizeof(struct ListNode));
temp->val =0;
temp->next= NULL;
struct ListNode * temp1 = NULL;
while(cur!=NULL)
{
if(count >=left&&count<=right)
{
struct ListNode * dd = (struct ListNode*)malloc(sizeof(struct ListNode));
dd->val = cur->val;
dd->next=temp->next;
temp->next = dd;
if(count==left)
{
temp1=dd;
}
cur=cur->next;
if(count==right)
{
temp1->next=cur;
break;
}
count++;
}
else{
last=cur;
cur=cur->next;
count++;
}
}
if(left==1)
{
head=temp->next;
//temp1->next=cur;
}
else
{
last->next = temp->next;
// temp1->next = cur;
// printf("%d",temp1->val);
// printf("%d",cur->val);
}
while(temp)
{
// printf("%d",temp->val);
temp=temp->next;
}
return head;
}