您的位置:首页 > 其它

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;

}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: