反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
方法一:简单粗暴,先遍历一遍,存在数组中,再新建一个单链表,赋值给新链表
/**
* 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) {
ListNode* ret = head;
ListNode* ret1 = ret;
int buf[10000];
int index = 0;
while(head){
buf[index++] = head->val;
head = head->next;
}
for(int i=0;i<index;i++){
ret1->val = buf[index-1-i];
ret1 = ret1->next;
}
return ret;
}
};
方法二:一个节点一个节点拆下来,组成新链表
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tail = 0;
while(head){
ListNode* tmp = head->next;
head->next = tail;
tail = head;
head = tmp;
}
return tail;
}
};