#include<iostream>
using namespace std;
typedef struct TNode
{
int data;
struct TNode* next;
}TNode;
TNode* createL(int n) //创建链表
{
TNode* head = NULL;
TNode* tial = NULL;
for (int i = 0; i < n; i++)
{
TNode* node = new TNode;
node->next = NULL;
cout << "请输入";
cin >> node->data;
if (head == NULL)
{
head = node;
tial = head;
}
else
{
tial->next = node;
tial = node;
}
}
tial->next = NULL;
return head;
}
void travel(TNode* head)
{
cout << "输出结果:" << endl;
TNode* p = head;
while (p != NULL)
{
cout << p->data << endl;
p = p->next;
}
}
TNode* reserve(TNode* head) //反转链表,返回翻转后的头结点
{
if (!head)
return head;
TNode* pre = head;
TNode* cur = head->next;
TNode* s;
while (cur != NULL)
{
s = cur->next;
cur->next = pre;
pre = cur;
cur = s;
}
head->next = NULL;
return pre;
}
int main()
{
TNode* head = NULL;
head = createL(7);
travel(head);
head = reserve(head);
travel(head);
return 0;
}
反转链表
最新推荐文章于 2025-03-12 20:11:42 发布