//可变数组(链表版)
#include<stdio.h>
#include<stdlib.h>
typedef struct _node
{
int value;
struct _node *next;
}Node;
typedef struct _list
{
Node * head;
}List;
void add(List *pList,int number);
void print(List *pList);
int main()
{
List list;
int number;
list.head=NULL;
do
{
scanf("%d",&number);
if(number!=-1)
{
add(&list,number);
}
}while(number!=-1);
print(&list);
scanf("%d",&number);
Node *p,*q;
for(q=NULL,p=list.head;p;q=p,p=p->next)
{
//利用双指针删除链表中与number相同的那一项
if(p->value==number)
{
if(q)//判断删除的是否为第一项
{
q->next=p->next;
}
else
{
list.head=p->next;
}
free(p);
break;
}
}
for(p=list.head;p;p=q)
//利用双指针清除链表
{
q=p->next;
free(p);
}
return 0;
}
void add(List *pList,int number)
{
//加入链表
Node *p=(Node*)malloc(sizeof(Node));
p->value=number;
p->next=NULL;
//找到最后一个结点
Node *last=pList->head;
if(last)//判断头指针是否为NULL
{
while(last->next)
{
last=last->next;
}//找到最后一个前停止
last->next=p;//指向最后一个
}
else
{
pList->head=p;
}
}
void print(List *pList)
{
Node *p;
for(p=pList->head;p;p=p->next)
//遍历链表
{
printf("%d ",p->value);
}
printf("\n");
}
C语言可变数组(链表版)
最新推荐文章于 2022-12-07 21:15:11 发布