2020-06-22
1.題目描述
定義一個函數,輸入一個鏈表的頭節點,反轉該鏈表並輸出反轉後鏈表的頭節點。
2.解答
直接進行反轉即可,注意不要讓鏈表斷了即可
3.代碼
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return NULL;
ListNode* p = head,*q=p->next,*t;
p->next=NULL;
while (q){
t=q->next;
q->next=p;
p=q;
q=t;
}
return p;
}
};