题解 | #反转链表#
反转链表
https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类
* @return ListNode类
*/
/* 法一:三指针反向*/
#include <stdio.h>
#include <stdlib.h>
#if 0
struct ListNode* ReverseList(struct ListNode* head ) {
// write code here
if(head ==NULL) return head;
struct ListNode *pre =NULL;
struct ListNode *nxt =NULL;
while (head != NULL)
{
nxt = head->next;
head->next = pre;
pre = head;
head = nxt;
}
return pre;
}
#endif
/* 法二:虚拟头 + 头插法 */
#if 1
struct ListNode* ReverseList(struct ListNode* head ) {
// write code here
if(head ==NULL) return head;
struct ListNode * virtual_head = malloc(sizeof(struct ListNode));//创建虚拟节点
virtual_head->next = head;
virtual_head->val = -1;
struct ListNode * cur =head->next;
struct ListNode * tail=head ;
//一个节点情况已排除,后续至少为两个实体节点。
//假设只有2个实体节点,只要保证nxt最多等于一次next就好了
while (cur!=NULL)
{
/* 3+1步:倒着处理单链表, 逐步交叉:该点next等于上一个 */
tail->next = cur->next;
cur->next = virtual_head->next;
virtual_head->next = cur;
//处理节点指针移动到下一个
cur = tail->next;
}
return virtual_head->next;
}
#endif
