LeetCode206—反转链表

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

 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* reverseList(ListNode* head) {
12         ListNode* prev = NULL;
13         ListNode* curr = head;
14         while (curr != NULL){
15             ListNode* nextTemp = curr->next;
16             curr->next = prev;
17             prev = curr;
18             curr = nextTemp;
19         }
20         return prev;
21     }
22 };
 1 //递归
 2 class Solution {
 3 public:
 4     ListNode* reverseList(ListNode* head) {
 5         if (head == NULL || head->next == NULL)
 6             return head;
 7         ListNode* p = reverseList(head->next);
 8         head->next->next = head;
 9         head->next = NULL;
10         return p;
11     }
12 };

猜你喜欢

转载自www.cnblogs.com/Jovesun/p/11823632.html
今日推荐