mirror of
https://github.com/ShusenTang/LeetCode.git
synced 2024-09-02 14:20:01 +00:00
Create 206. Reverse Linked List.md
This commit is contained in:
parent
9f5390f7a2
commit
7b1646ab62
63
206. Reverse Linked List.md
Normal file
63
206. Reverse Linked List.md
Normal file
@ -0,0 +1,63 @@
|
||||
# [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/description/)
|
||||
# 思路
|
||||
## 思路一:迭代
|
||||
先设置一个头结点List_head,其next指向NULL。然后从待翻转链表中一次取一个节点p出来,将p的next指向List_head的next,List_head的next指向p。
|
||||
循环上述操作直到p为NULL。
|
||||
## 思路二:递归
|
||||
也可以采用递归的方式:
|
||||
* 递归出口:若head == NULL 或者 head -> next == NULL,直接返回head即可;
|
||||
* 递归主体:用q记录head的下一个节点,然后令p等于reverseList(q),则p的最后一个非空节点就是q,将q的next令为head,head的next令为NULL,再返回p即可。
|
||||
|
||||
# C++
|
||||
## 思路一
|
||||
```
|
||||
/**
|
||||
* 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) {
|
||||
ListNode *List_head = new ListNode(0);
|
||||
List_head -> next = NULL;
|
||||
|
||||
ListNode *p = head, *tmp;
|
||||
while(p){
|
||||
tmp = p -> next;
|
||||
p -> next = List_head -> next;
|
||||
List_head -> next = p;
|
||||
p = tmp;
|
||||
}
|
||||
return List_head -> next;
|
||||
|
||||
}
|
||||
};
|
||||
```
|
||||
## 思路二
|
||||
```
|
||||
/**
|
||||
* 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 == NULL || head -> next == NULL) return head;
|
||||
ListNode *p, *q;
|
||||
|
||||
q = head -> next;
|
||||
p = reverseList(q);
|
||||
q -> next = head;
|
||||
head -> next = NULL;
|
||||
return p;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in New Issue
Block a user