-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path206.反转链表.cpp
84 lines (73 loc) · 1.79 KB
/
206.反转链表.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
* @lc app=leetcode.cn id=206 lang=cpp
*
* [206] 反转链表
*/
// @lc code=start
//Definition for singly-linked list.
#include<iostream>
#include<algorithm>
using namespace std;
// struct ListNode {
// int val;
// ListNode *next;
// ListNode(int x) : val(x), next(NULL) {}
// };
// class Solution {
// public:
// ListNode* reverseList(ListNode* head) {
// ListNode *p = head;
// ListNode *cur=NULL;
// while(p!=NULL){
// ListNode *q = new ListNode(p->val);
// q->next = cur;
// cur = q;
// p = p->next;
// }
// return cur;
// }
// };
// class Solution {
// public:
// ListNode* reverseList(ListNode* head) {
// if(head==NULL){
// ListNode *p=NULL;
// return p;
// }
// ListNode *q = reverseList(head->next);
// if(q == NULL){
// q = new ListNode(head->val);
// }else{
// ListNode *cur = q;
// while(cur->next!=NULL){
// cur = cur->next;
// }
// cur->next = new ListNode(head->val);
// }
// return q;
// }
// };
class Solution {
public:
// ListNode* reverseList(ListNode* head) {
// ListNode* cur=head;
// ListNode* pre=NULL;
// ListNode* temp;
// while(cur!=NULL){
// temp = cur->next;
// cur->next=pre;
// pre=cur;
// cur=temp;
// }
// return pre;
// }
ListNode* reverseList(ListNode* head) {
if(head==NULL)return head;
if(head->next==NULL)return head;
ListNode* last = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return last;
}
};
// @lc code=end