剑指offer15-反转链表
最近全国疫情严重,待在家里没事干,马上又要准备春招了,最近刷刷题,记录一下!再说一句,武汉加油,大家出门记得戴口罩!
1、题目描述
输入一个链表,反转链表后,输出新链表的表头。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
2、思路
3、代码
c++
class Solution {
public:
ListNode* reverseList(ListNode* head) {
//判断边界
if(!head) return NULL;
auto a=head,b=head->next;
while(b!=NULL)
{
auto c=b->next;
b->next=a;
a=b;
b=c;
}
head->next=NULL;
return a;
}
};
Java
class Solution {
public ListNode reverseList(ListNode head) {
//申请节点,a和 b,c
if(head==null) return null;
ListNode a=head,b=head.next;
while(b!=null) {
ListNode c=b.next;
b.next=a;
a=b;
b=c;
}
head.next=null;
return a;
}
}