链表反转

定义一个函数,输入一个链表的头节点,反转该链表并输出反转后链表的头节点。
 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverse(ListNode* cur, ListNode* pre) {
12         if (cur == NULL) {
13             return pre;
14         }
15         ListNode* res = reverse(cur->next, cur);
16         cur->next = pre;
17         return res;
18     }
19     /*这里返回 res 是为了在链表多次递归返回后依旧能够保存递归深层次的链表节点值*/
20     ListNode* reverseList(ListNode* head) {
21         ListNode* res = reverse(head, NULL);
22         return res;
23     }
24 };

 

posted @ 2021-03-06 23:17  HuLargeSun  阅读(75)  评论(0)    收藏  举报