- 题目:
反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
- 解题思路1(递归)
递归式
ListNode* reverseList(ListNode* head) {
if(head == nullptr || head->next == nullptr) //递归出口,空节点,一个节点则返回
return head;
ListNode *newhead = reverseList(head->next); //反转除头节点之后节点。
head->next->next = head; //第二个节点指向节点
head->next = nullptr; //头节点指向空
return newhead;
}
- 解题思路二(迭代)
参考:https://www.cnblogs.com/seniusen/p/9781153.html
代码实现(C++)
ListNode* reverseList(ListNode* head) {
ListNode *p1,*p2,*p3;
if(head == nullptr || head->next == nullptr)
return head;
else{
p1 = head;
p2 = head->next;
p3 = head->next->next;
while(p2 != nullptr)
{
p3 = p2->next;
p2->next = p1;
p1 = p2;
p2 = p3;
}
head->next = nullptr;
head = p1;
}
return head;
}