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++)
利用迭代的方法依次将链表元素放在新链表的最前端实现链表的倒置
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head) { 4 ListNode* newhead=NULL; 5 while(head){ 6 ListNode* t=head->next; 7 head->next=newhead; 8 newhead=head; 9 head=t; 10 } 11 return newhead; 12 } 13 };
解法二(C++)
并不是多么正统的方法,借助vector的先进后出的方法实现倒置
1 class Solution { 2 public: 3 ListNode* reverseList(ListNode* head) { 4 if(!head||!head->next) 5 return head; 6 vector<int> m; 7 while(head){ 8 m.push_back(head->val); 9 head=head->next; 10 } 11 ListNode* newhead=new ListNode(-1); 12 ListNode* t=newhead; 13 while(!m.empty()){ 14 ListNode* cur=new ListNode(m.back()); 15 m.pop_back(); 16 t->next=cur; 17 t=cur; 18 } 19 return newhead->next; 20 } 21 };