由于作者能力有限,第一次写的时候并没有考虑到头结点,无法很好的解决不同情况下返回head的问题,几次提交的结果都是失败,在看了大佬们的解题方法。谈不上分享,算是记录。
方法:头插迭代法
在链表前加一个表头(定位头结点),定义两个指针cur和next,一个指向当前节点,一个指下一个节点,遍历到m的位置时,后续采取头插,考虑好节点的指针指向,就可以实现指定区域的反转了。
图解:
代码实现:
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
#include <stdio.h>
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
// write code here
if(m==n)
{
return head;
}
if(head == NULL)
{
return head;
}
struct ListNode* phead = (struct ListNode*)malloc(sizeof(struct ListNode));
phead->val = 666;
phead->next = head;
struct ListNode*prev = phead;
int i=0;
for(i=0;i<m-1;i++)
{
prev = prev->next;
}
struct ListNode* cur = prev->next;
struct ListNode* next ;
for(i=0;i<n-m;i++)
{
next = cur->next;
cur->next = next->next;
next->next = prev->next;
prev->next = next;
}
return phead->next;
}
今天的分享就到这里,希望大家一起提高!!!