#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *next;
}Node;
typedef struct Node *LinkList;
void CreateListEnd(LinkList *head);
void PrintList(LinkList head);
void InsertList(LinkList *head,int index,int e);
void DeleteList(LinkList *head,int index);
void DeleteWholeList(LinkList *head);
void CreateListHead(LinkList *head);
int main(void)
{
LinkList head=NULL;
CreateListHead(&head);
PrintList(head);
//InsertList(&head,10,100);
//PrintList(head);
DeleteList(&head,3);
PrintList(head);
//DeleteWholeList(&head);
//PrintList(head);
system("pause");
return 0;
}
void CreateListHead(LinkList *head)
{
Node *s;
*head=(Node *)malloc(sizeof(Node));
(*head)->next=NULL;
int num;
printf("请输入你要生成的节点个数\n");
scanf("%d",&num);
int i;
for(i=0;i<num;i++)
{
s=(Node *)malloc(sizeof(Node));
s->data=i+1;
s->next=(*head)->next;
(*head)->next=s;
}
}
void CreateListEnd(LinkList *head)
{
Node *tail,*s;
*head=(Node *)malloc(sizeof(Node));
(*head)->next=NULL;
if(*head==NULL)
{
printf("内存分配失败\n");
}
tail = *head;
int num;
printf("请输入你要生成的节点个数\n");
scanf("%d",&num);
int i;
for(i=0;i<num;i++)
{
s=(Node *)malloc(sizeof(Node));
s->data = i+1;
tail->next=s;
tail=s;
}
tail->next=NULL;
}
void PrintList(LinkList head)
{
Node *p;
int index=1;
for(p=head->next;p;p=p->next)
{
printf("%d----%d\n",index,p->data);
index++;
}
}
void InsertList(LinkList *head,int index,int e)
{
if(index<1)
printf("插入位置不合法\n");
Node *p,*s;
p=*head;
int j=1;
while(p && j<index)
{
p=p->next;
j++;
}
if(!p)
{
printf("%d位置不合法\n",index);
}
s=(Node *)malloc(sizeof(Node));
s->data = e;
s->next=p->next;
p->next=s;
}
void DeleteList(LinkList *head,int index)
{
if(index<1)
printf("%d值不合法\n",index);
int j=1;
Node *p=*head;
while(p && j<index)
{
p=p->next;
j++;
}
if(p==NULL) //i值不合法
return 0;
if(p->next==NULL)
{
printf("%d个节点之后已无节点\n",index-1);
}
Node *q;
q=p->next;
p->next=q->next;
printf("删除节点的数据是%d\n",q->data);
free(q);
}
void DeleteWholeList(LinkList *head)
{
Node *p,*q;
for(p=(*head)->next;p;p=q)
{
q=p->next;
printf("删除节点的数据是%d\n",p->data);
free(p);
}
(*head)->next=NULL;
}
链表
最新推荐文章于 2023-01-01 14:24:44 发布