目录
1、题目来源
206. 反转链表 - 力扣(LeetCode)https://leetcode.cn/problems/reverse-linked-list/
2、函数介绍
给你单链表的头节点
head
,请你反转链表,并返回反转后的链表。
3、问题示例
4、函数实现
1、翻指针方向
思路一:翻指针方向
重复的过程用循环解决
1、初始条件
2、迭代过程
3、结束条件
代码实现
struct ListNode* reverseList(struct ListNode* head)
{
if(head==NULL) return NULL;
//初始条件
struct ListNode* n1=NULL,*n2=head,*n3=n2->next;
//结束条件
while(n2)
{
n2->next=n1;
n1=n2;
n2=n3;
if(n3) n3=n3->next;
}
return n1;
}
2、头插法
取原链表的节点,头插到新链表中
代码实现
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* cur=head;
struct ListNode* newHead=NULL;
while(cur)
{
struct ListNode* next=cur->next;
//头插
cur->next=newHead;
newHead=cur;
cur=next;
}
return newHead;
}