【剑指offer 面试题16】反转链表

时间:2023-11-22 12:42:44

思路:

  用三个指针preNode、curNode、nextNode完成。

 #include <iostream>
using namespace std; struct ListNode
{
int val;
ListNode *next;
ListNode(int v = ):val(v), next(NULL){}
}; ListNode* reverseList(ListNode **pListhead)
{
//条件不加也不会出错,突出边界测试的想法
if(*pListhead == NULL)
return NULL;
if((*pListhead)->next == NULL)
return *pListhead; ListNode *preNode = NULL;
ListNode *curNode = *pListhead;
ListNode *reverseHead = NULL; while(curNode != NULL)
{
ListNode *nextNode = curNode->next; if(nextNode == NULL)
{
reverseHead = curNode;
} curNode->next = preNode; preNode = curNode;
curNode = nextNode;
} return reverseHead;
} int main()
{
ListNode *head = new ListNode();
ListNode *phead = head; for(int i = ; i < ; i++)
{
ListNode *temp = new ListNode(i);
phead->next = temp;
phead = phead->next;
} cout<<"原始链表: ";
ListNode *print = head;
while(print != NULL)
{
cout<<print->val<<" ";
print = print->next;
}
cout<<endl; cout<<"反转链表: ";
ListNode *rehead = reverseList(&head);
while(rehead != NULL)
{
cout<<rehead->val<<" ";
rehead = rehead->next;
}
} 测试结果:
原始链表:
反转链表: