力扣刷题—链表反转

法一:反转指针

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/


struct ListNode* reverseList(struct ListNode* head){
if(head==NULL)
return NULL;

struct ListNode*n1=NULL;//n1作为返回的头节点
struct ListNode*n2=head;
struct ListNode*n3=n2->next;//记录头节点的下一个节点,避免转过去之后找不到后面的节点


while(n2)//n2是反转的主角,所以n2到空才可以,迭代过程
{
n2->next=n1;
n1=n2;
n2=n3;
if(n3)
n3=n3->next;
}
return n1;


}

 法二:头插法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/


struct ListNode* reverseList(struct ListNode* head){
if(head==NULL)
return NULL;
struct ListNode*cur=head;
struct ListNode*newnode=NULL;
struct ListNode*next=cur->next;
while(cur)
{
cur->next=newnode;
newnode=cur;
cur=next;
if(next)
next=next->next;

}
return newnode;

}

力扣刷题—链表反转
http://example.com/2021/11/11/力扣刷题—链表反转/
作者
Zevin
发布于
2021年11月11日
许可协议