1、在链表前加一个表头,后续返回时去掉就好了,因为如果要从链表头的位置开始反转,在多了一个表头的情况下就能保证第一个节点永远不会反转,不会到后面去。
2、使用两个指针,一个指向当前节点,一个指向前序节点。
3、依次遍历链表,到第m个的位置
4、对于从m到n这些个位置的节点,依次断掉指向后续的指针,反转指针方向。
5、返回时去掉我们添加的表头。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @param m int整型
* @param n int整型
* @return ListNode类
*/
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
// write code here
struct ListNode res;
struct ListNode *cur = head;
struct ListNode *pre = &res;
struct ListNode *temp = NULL;
int i = 0;
pre->next = cur;
//找到m节点,m节点之前不反转
for(i = 1; i < m; i++ )
{
pre = cur;
cur = cur->next;
}
for( i = m; i < n; i++)
{
temp = cur->next;
cur->next = temp->next;
temp->next = pre->next;
pre->next = temp;
}
return res.next;
}