#include<stdio.h>
#include<malloc.h>
struct node {
int data;
struct node *next;
};
struct node *head,*tail,*p;
int n=0;
void creatNode();
int length();
int outNode(int i);
void insertNode(int i,int dta);
void print();
void delNode(int i);
int isNull();
void main() {
int i, nodeLength;
printf("初始化5个链表\n");
for(i=1; i<=5; i++) {
creatNode();
printf("输入data:");
scanf("%d", &tail->data);
}
//初始化完毕
//求链表长度
nodeLength = length();
printf("链表长度为:%d\n", nodeLength);
//取第三个元素
printf("第三个元素为:%d\n", outNode(3));
printf("在第3个元素前插入888\n");
insertNode(3, 888);
print();
printf("删除第3个节点\n");
delNode(3);
print();
printf("链表是否为空:%s\n", isNull()==0?"YES":"NO");
}
void creatNode() {
struct node *p0;
p0 = (struct node*)malloc(sizeof(struct node));
p0->next = NULL;
if(p0 == NULL)
printf("ERROR!");
if(head == NULL) {
head = p0;
tail = p0;
//n ++;
}
tail->next = p0;
tail = p0;
//n ++;
}
int length() {
int n = 1;
struct node *pt;
pt = head;
while(pt->next != NULL){
n ++;
pt = pt->next;
}
return n;
}
//取出第i个个元素
int outNode(int i) {
int k=1;
struct node *pt;
pt = head;
//if(i>lgh) {
//printf("所寻元素超出范围\n");
//return
//}
while(k<i) {
pt = pt->next;
k ++;
}
return pt->data;
}
void print() {
struct node *pt;
pt = head;
while(1) {
printf("%d ", pt->data);
if(pt->next == NULL) break;
pt = pt->next;
}
printf("\n");
}
//在第i个数前面插入一个数
void insertNode(int i,int dta) {
struct node *pt, *pd, *da;
int k=1;
da = (struct node*)malloc(sizeof(struct node));
da->next = NULL;
da->data = dta;
pt = head;
while(k<i) {
pd = pt;
pt = pt->next;
k ++;
}
pd->next = da;
da->next = pt;
}
void delNode(int i) {
struct node *pt, *pd;
int k=1;
pt = head;
while(k<i) {
pd = pt;
pt = pt->next;
k ++;
}
pd->next = pt->next;
}
int isNull() {
if(head == tail)
return 0;
return 1;
}
【数据结构】链表
最新推荐文章于 2022-04-29 09:49:24 发布