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;
}
};