LeetCode 206. Reverse Linked List倒置链表 C++

Reverse a singly linked list.

Example:

Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

解法一:(C++)
利用迭代的方法依次将链表元素放在新链表的最前端实现链表的倒置
 class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* newhead=NULL;
while(head){
ListNode* t=head->next;
head->next=newhead;
newhead=head;
head=t;
}
return newhead;
}
};

解法二(C++)

并不是多么正统的方法,借助vector的先进后出的方法实现倒置

 class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head||!head->next)
return head;
vector<int> m;
while(head){
m.push_back(head->val);
head=head->next;
}
ListNode* newhead=new ListNode(-);
ListNode* t=newhead;
while(!m.empty()){
ListNode* cur=new ListNode(m.back());
m.pop_back();
t->next=cur;
t=cur;
}
return newhead->next;
}
};
上一篇:基于CSOCKET的Client简单实例(转)


下一篇:leetcode 206. Reverse Linked List(剑指offer16)、