题目来源:力扣
题目描述:
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
本题有两种解法
目录
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
示例 2:
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
代码1:
struct ListNode* reverseList(struct ListNode* head){
if(head==NULL){
return NULL;
}
struct ListNode* cur,*prev,*next;
prev=NULL;
cur=head;
next=cur->next;
while(cur){
cur->next=prev;
prev=cur;
cur=next;
if(cur==NULL){
break;
}
next=cur->next;
}
return prev;
}
思路:反转指针,1->2->3->4->5->NULL的链表,我们将指针反转,变为:NULL<-1<-2<-3<-4<-5,我们使用三个变量来进行控制,使prev最开始为空,cur为head,next为cur的next,然后我们进行反转,将cur的next指向prev,接着我们进行迭代,将三个指针向后移动,当cur为空时结束,我们返回prev即可,接着对特殊情况进行处理,如cur到达尾时,next为空,再次进行迭代时,cur为空,next的next是空指针问题,所以我们在while循环里对cur进行判断,接着就是对空链表进行判断即可
代码2:
struct ListNode* reverseList(struct ListNode* head){
struct ListNode* newhead=NULL;
struct ListNode* cur=head;
while(cur){
struct ListNode* next=cur->next;
cur->next=newhead;
newhead=cur;
cur=next;
}
return newhead;
}
思路:取节点头插到新的头,比如链表是1,2,3,4,5,我们取下1头插到一个新的头,接着将2头插到1前面,反复循环即可,并且最开始newhead为NULL,链表如果为空,循环也不会进去,所以我们也不需要判空