一道经典的数据结构初学者问题,主要考察指针的修改和用法:
就像题目中进阶要求所说的那样,这道题有两种解法:迭代和递归。但其实它们的核心操作都是一样的,就是代码中修改指针的部分,当然这题需要一前一后两个指针跟随着一步步将链表逆置。
下面贴出我的代码,首先是递归写法:
// recursive method
void recursive(ListNode*& Ahead, ListNode*& Follow)
{
if(Ahead == nullptr)
return;
/*store the Ahead->next pointer*/
ListNode* Tmp = Ahead->next;
/*modify the pointer*/
Ahead->next = Follow;
Follow = Ahead;
Ahead = Tmp;
recursive(Ahead, Follow);
}
// start of the main function
ListNode* reverseList(ListNode* head)
{
if(head == nullptr)
return head;
/*recursive method*/
ListNode* Ahead = head->next;
ListNode* Follow = head;
/*set the first node's next to nullptr*/
Follow->next = nullptr;
recursive(Ahead, Follow);
return Follow;
}
其次是迭代的写法:
ListNode* reverseList(ListNode* head)
{
if(head == nullptr)
return head;
/*iterative method*/
ListNode* Ahead = head->next;
ListNode* Follow = head;
/*set the first node's next to nullptr*/
Follow->next = nullptr;
while(Ahead)
{
/*store the next pointer*/
ListNode* Tmp = Ahead->next;
Ahead->next = Follow;
Follow = Ahead;
Ahead = Tmp;
}
return Follow;
}
可以看到核心部分代码都是下面这几步,当然还有不要忘记将第一个结点的next指针指向nullptr:
ListNode* Tmp = Ahead->next;
Ahead->next = Follow;
Follow = Ahead;
Ahead = Tmp;