反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
方法1:
设置三个指针进行反转,one和two负责反转,three负责暂存下一个位置。
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode *one=head, *two=one->next, *three=two->next;
head->next = NULL;
while (two) {
two->next = one;
one = two;
two = three;
if (three) three = three->next;
}
return one;
}
方法2:递归
关键点在于要记录尾结点,并且head->next要置空,否则在修改时会出问题
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
ListNode* tail = reverseList(head->next);//记录尾结点
head->next->next = head;
head->next = NULL;
return tail;
}