题目 反转链表
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
递归法
struct ListNode* ret;
int buf;
int count;
void __reverseList(struct ListNode* head) {
if(head->next) {
__reverseList(head->next);
}
if(count > 0){
count--;
buf = ret->val;
ret->val = head->val;
head->val = buf;
ret = ret->next;
}
}
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* bufNode = head;
if(!head)
return head;
if(!head->next)
return head;
count = 0;
while(bufNode) {
bufNode = bufNode->next;
count++;
}
ret = head;
count /= 2;
__reverseList(head);
return head;
}
迭代法
struct ListNode* reverseList(struct ListNode* head) {
struct ListNode* ret;
struct ListNode* preNode = NULL;
struct ListNode* bufNode;
if(!head)
return head;
if(!head->next)
return head;
while(head)
{
bufNode = head->next;
head->next = preNode;
preNode = head;
head = bufNode;
}
return preNode;
}