#include<stdio.h>
#include<stdlib.h>
#define SIZE sizeof(struct linklist)
struct linklist
{
int x;
struct linklist* next;
};
int main(void)
{
int n,i,j;
struct linklist *first,*p1,*p2,*p3;
first = (struct linklist*)malloc(SIZE);// 创建头节点
if (first == NULL)
{
printf("error\n");
return -1;
} // 头节点创建成功
printf("please inpput n\n");
while (1) {
if (scanf_s("%d", &n) == 1 && n > 0)
{
break; //需要输入多少数据
}
}
i = n;
while(i)
{
p1 = (struct linklist*)malloc(SIZE);//生成新的节点
if (p1 == NULL)
{
printf("error\n");
return -1;
}
scanf_s("%d", &p1->x); //输入元素值赋值给新节点的数据域
if (i == n) //第一个新节点应该链接头结点的指针域
{
first->next = p1;
p2 = p1; //用指针p2记录新节点的地址
}
else //第二个节点及后面节点
{
p2->next = p1; //将上一个新节点的指针域链接新节点
p2 = p1; //利用指针p2记录新节点的地址
}
i--;
if (i == 0) //将最后一个节点的指针域赋值为NULL以代表链表结束
{
p2->next = NULL;
}
}
//链表元素的输出
p1 = first->next;
while (1)
{
printf("%d\n", p1->x);
p1 = p1->next;
if (p1 == NULL)
break;
}
//
//单链表的取值
printf("look dijigeyuansu i:");
while(1)
{
scanf_s("%d",&i);
if(i<=n&&0<i)
{
break;
}
else
{
continue;
}
}
j=1;
p1=first->next;
while(1)
{
if(i==j)
{
printf(" is %d\n",p1->x);
break;
}
else
{
p1=p1->next;
j++;
}
}
/
//新节点的插入
printf("insert i:");
while(1)
{
scanf_s("%d",&i);
if(i<n&&0<i)
{
break;
}
else
{
continue;
}
}
j=1;
p1=first->next;
while(1)
{
if(j==i)
{
p2=p1->next;
p3=(struct linklist*)malloc(SIZE);
if(p3==NULL)
return -1;
scanf("%d",&p3->x);
p1->next=p3;
p3->next=p2;
break;
}
p1=p1->next;
j++;
}
n++;
//链表元素的输出
p1 = first->next;
while (1)
{
printf("%d\n", p1->x);
p1 = p1->next;
if (p1 == NULL)
break;
}
//
//节点的删除
printf("delete i:");
scanf("%d",&i);
j=1;
p1=first->next;
while(1)
{
if(j==i)
{
p2=p1->next;
p3=p2->next;
p1->next=p3;
break;
}
p1=p1->next;
j++;
}
n--;
//链表元素的输出
p1 = first->next;
while (1)
{
printf("%d\n", p1->x);
p1 = p1->next;
if (p1 == NULL)
break;
}
//
//程序结束
return 0;
}