反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
这题也蛮简单的,但是一开始由于混淆地址,tmp = p, tmp->next=..., p = p->next, 这样写的话tmp由于是跟p地址相同,改变tmp的next也等于改变了p的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) {
ListNode *p = head, *tmp=NULL, *ptmp=NULL;
while (p){
tmp = p->next;
p->next = ptmp;
ptmp = p;
p = tmp;
}
return ptmp;
}
};
递归:
/**
* 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->next == NULL)
return head;
ListNode *p = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return p;
}
};
emmmmm递归的结果是对的,但是过不了,说什么runtime error: member access within null pointer of type……,查了下原因说不能引用空指针……???好吧,我不知道怎么改,再说吧……反正测试样例是通过的……