赞
踩
题目描述:给你单链表的头节点 head
,请你反转链表,并返回反转后的链表
leetcode链接:
力扣
思路一:链表的头插。由于改变了cur->next,因此需要记住cur->next的位置
图片:
代码:
- class Solution {
- public:
- ListNode* reverseList(ListNode* head) {
- if(head==NULL)
- {
- return NULL;
- }
- struct ListNode*cur=head;
- struct ListNode*newhead=NULL;
- struct ListNode*next=cur->next;
-
- while(cur)
- {
- cur->next=newhead;
-
- newhead=cur;
- cur=next;
- if(next)
- next=next->next;
- }
- return newhead;
- }
- };

思路二:指针的倒置,改变指针的方向反转单链表。
需要注意的是:对于空链表的处理,以及运行时next的处理。
图:
代码:
- class Solution {
- public:
- ListNode* reverseList(ListNode* head) {
-
- if(head==NULL)
- {
- return NULL;
- }
-
- struct ListNode*cur=head;//用于记住当前的位置
- struct ListNode*next=cur->next;//用于记住下一个结点的位置,否则倒转next的指向之后,无法找到下一个结点的位置
- struct ListNode*newhead=NULL;//从NULL开始,因为原链表是以NULL结束的,用于返回逆置后的头节点
-
-
-
- while(cur)
- {
- cur->next=newhead;//倒转指针的指向
- //迭代
- newhead=cur;
- cur=next;
- if(next)//注意判断条件是while(cur),因此cur最终走到null结束,那么next=next->next会出现空指针的问题,需要判断
- next=next->next;
- }
-
- return newhead;
- }
- };

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。