LeetCode 206. 反轉連結串列
阿新 • • 發佈:2021-01-19
技術標籤:# 連結串列# leetcode
反轉一個單鏈表。
示例:
輸入: 1->2->3->4->5->NULL
輸出: 5->4->3->2->1->NULL
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* rev(ListNode*pre,ListNode*now) {
if(now == NULL) return NULL;
ListNode*nex = now -> next;
now -> next = pre;
if(nex == NULL) {
return now;
}
return rev(now,nex);
}
ListNode* reverseList(ListNode* head) {
return rev(NULL ,head);
}
};