LeetCode206-反轉鏈表
最近全國疫情嚴重,待在家裏沒事幹,馬上又要準備春招了,最近刷刷題,記錄一下!再說一句,武漢加油,大家出門記得戴口罩!
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;
}
}