LeetCode/solutions/206. Reverse Linked List.md
2019-09-13 23:08:41 +08:00

64 lines
1.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# [206. Reverse Linked List](https://leetcode.com/problems/reverse-linked-list/description/)
# 思路
## 思路一:迭代
先设置一个头结点List_head其next指向NULL。然后从待翻转链表中一次取一个节点p出来将p的next指向List_head的nextList_head的next指向p。
循环上述操作直到p为NULL。
## 思路二:递归
也可以采用递归的方式:
* 递归出口若head == NULL 或者 head -> next == NULL直接返回head即可
* 递归主体用q记录head的下一个节点然后令p等于reverseList(q)则p的最后一个非空节点就是q将q的next令为headhead的next令为NULL再返回p即可。
# C++
## 思路一
``` 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;
}
};
```
## 思路二
``` 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) {
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;
}
};
```