练习:链表反转
一、描述
输入一个链表,反转链表后,输出新链表的表头。
二、非递归方法
代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL) return pHead;
ListNode *p = pHead, *q = pHead;
ListNode *newHead = NULL;
while(p) {
q = p->next;
p->next = newHead;
newHead = p;
p = q;
}
return newHead;
}
};
三、递归方法
Node* reverse(Node* head) {
if(head == nullptr) return nullptr;
if(head->next == nullptr) return head;
Node* newhead = reverse(head->next);
head->next->next = head;
head->next = nullptr;
return newhead;
}