#include <stdio.h>
#include <iostream>
using namespace std;
#include <stdlib.h>
typedef struct LNode
{
int data;
struct LNode *next;
} LNode, *LNodeList;
void InitList_Head(LNodeList &L) // 头插法
{
L = new LNode;
L->data = 0;
L->next = NULL;
for (int i = 0; i < 10; i++)
{
LNodeList s = new LNode;
s->data = i;
s->next = L->next;
L->next = s;
}
}
void InitList_Tear(LNodeList &L) // 尾插法
{
int flag = 999;
int i = 1;
L = new LNode;
// L->data = 0;
LNodeList r = L;
L->next = NULL;
while (1)
{
LNodeList s = new LNode;
printf("请输入%d个关键字:", i);
scanf("%d", &s->data);
// cin >> s->data;
// s->data = i;
if (flag == s->data)
{
break;
}
s->next = nullptr;
r->next = s;
r = s;
i++;
}
}
void printfList(LNodeList L) // 打印单链表
{
LNodeList q = L->next;
int i = 0;
while (q != NULL)
{
printf("%d ", q->data);
i++;
q = q->next;
}
printf("单链表长度:%d\n", i);
}
void ReverseList(LNodeList &L)
{
LNodeList q = L->next;
LNodeList r = L->next->next;
L->next = nullptr;
while (r)
{
q->next = L->next;
L->next = q;
q = r;
r = r->next;
}
q->next = L->next;
L->next = q;
}
int main()
{
LNodeList A;
// InitList_Head(myList1); // 头插法
InitList_Tear(A); // 尾插法
printfList(A);
ReverseList(A);
printf("逆序输出单链表:");
printfList(A);
}
运行结果如下