- 论坛徽章:
- 1
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef int Data;
struct Node
{
Data data;
struct Node *next;
};
struct List
{
struct Node *head;
char name[20];
};
void SetName(struct List *const this,const char *p)
{
strcpy(this->name, p);
}
void Print(struct List *const this)
{
system("cls");
puts(this->name);
struct Node *p = this->head;
while (p)
{
printf("%d\n", p->data);
p = p->next;
}
system("pause");
}
int GetCount(struct List *const this)
{
struct Node *p = this->head;
int i = 0;
while (p)
{
p = p->next;
i++;
}
return i;
}
void AddHead(struct List *const this, Data data)
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = this->head;
this->head = p;
}
void AddTail(struct List *const this, Data data)
{
struct Node *p = (struct Node*)malloc(sizeof(struct Node));
p->data = data;
p->next = NULL;
if (!this->head)
{
this->head = p;
return;
}
struct Node *q = this->head;
while (q->next)
{
q = q->next;
}
q->next = p;
}
void RemoveAll(struct List *const this)
{
struct Node *p = this->head, *q;
while (p)
{
q = p;
p = p->next;
free(q);
}
this->head = NULL;
}
void AddData(struct List *const this)
{
Data data;
system("cls");
printf("请输入一个整数:");
scanf("%d", &data);
AddTail(this,data);
}
void Menu(struct List *const this)
{
system("cls");
printf("1.插入数据\n");
printf("2.打印数据\n");
printf("3.打印节点数量\n");
int i;
scanf("%d", &i);
switch (i)
{
case 1:
AddData(this);
break;
case 2:
Print(this);
break;
case 3:
system("cls");
printf("当前结点数量:%d\n", GetCount(this));
system("pause");
break;
default:
break;
}
}
List(struct List *const this)
{
this->head = NULL;
}
DeList(struct List *const this)
{
RemoveAll(this);
}
int main(int argc,char *argv[])
{
struct List list_1, list_2;
List(&list_1);
SetName(&list_1, "list_1");
List(&list_2);
SetName(&list_2, "list_2");
int i = 0;
do {
system("cls");
printf("1.->链表一2.->链表二\n");
printf("请选择:");
fflush(stdin);
scanf("%d",&i);
switch (i)
{
case 1:
Menu(&list_1);
break;
case 2:
Menu(&list_2);
break;
default:
break;
}
} while (i);
DeList(&list_1);
DeList(&list_2);
return 0;
} |
|