#include<iostream>
using namespace std;
struct ListNode
{
int val;
ListNode* next;
};
//反转链表
ListNode* reverseList(ListNode* pHead)
{
if (!pHead || !pHead->next)
return pHead;
ListNode* tail = reverseList(pHead->next);
pHead->next->next = pHead;
pHead->next = NULL;
return tail;
}
//打印链表
void printList(ListNode* head)
{
while (head)
{
cout << head->val;
head = head->next;
if (head)
cout << "->";
}
cout << endl;
}
int main()
{
//创建链表
ListNode* head = NULL;
ListNode* cur = NULL;
for (int i = 1; i <= 5; ++i)
{
ListNode* node = new ListNode;
node->val = i;
node->next = NULL;
if (head == NULL)
{
head = node;
cur = node;
}
else
{
cur->next = node;
cur = node;
}
}
printList(head);
printList(reverseList(head));
return 0;
}
C++反转链表完整代码
最新推荐文章于 2023-10-25 00:44:34 发布