Reverse Linked List
2018-03-13 10:43
162 查看
Description: Reverse a singly linked list.
思路1:使用栈结构实现反转,先遍历一遍list,依次入栈,然后依次出栈,重新建立list/**
* 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)
return head;
ListNode* res = NULL;
ListNode* p = NULL;
stack<int> mystack;
while(head != NULL)
{
mystack.push(head->val);
head = head->next;
}
while(!mystack.empty())
{
int val = mystack.top();
ListNode* tmp = new ListNode(val);
if(!res)
res = tmp;
if(p)
p->next = tmp;
p = tmp;
mystack.pop();
}
return res;
}
};思路2:不使用栈进行交换,定义指针记录当前指针,并将当前指针的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* tail = NULL;
ListNode* curr = head;
while(curr != NULL)
{
ListNode* tmp = curr->next;
curr->next = tail;
tail = curr;
curr = tmp;
}
return tail;
}
};
思路1:使用栈结构实现反转,先遍历一遍list,依次入栈,然后依次出栈,重新建立list/**
* 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)
return head;
ListNode* res = NULL;
ListNode* p = NULL;
stack<int> mystack;
while(head != NULL)
{
mystack.push(head->val);
head = head->next;
}
while(!mystack.empty())
{
int val = mystack.top();
ListNode* tmp = new ListNode(val);
if(!res)
res = tmp;
if(p)
p->next = tmp;
p = tmp;
mystack.pop();
}
return res;
}
};思路2:不使用栈进行交换,定义指针记录当前指针,并将当前指针的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* tail = NULL;
ListNode* curr = head;
while(curr != NULL)
{
ListNode* tmp = curr->next;
curr->next = tail;
tail = curr;
curr = tmp;
}
return tail;
}
};
相关文章推荐
- leetcode 92. Reverse Linked List II
- Reverse Second Half of a Linked List
- Reverse Linked List II
- Reverse Linked List II
- 206. Reverse Linked List
- Leetcode:Reverse Linked List II 单链表区间范围内逆置
- [LeetCode]Reverse Linked List II解题报告
- 206. Reverse Linked List
- LeetCode: Reverse Linked List II [092]
- leetcode[92]Reverse Linked List II
- Reverse Half LinkedList
- [LeetCode] Reverse Linked List
- Reverse Linked List II
- [LeetCode-206] Reverse Linked List(链表反转)
- [Lintcode]Reverse Linked List
- 【Hackerrank】Reverse a doubly linked list
- Leetcode: Reverse Linked List II
- LeetCode 206. Reverse Linked List
- LeetCode_206 Reverse Linked List
- Reverse Linked List II