#include <stdio.h>
#include <stdlib.h>
typedef int T;
struct node
{
T data;
struct node* next;
};
typedef struct node Node;
#define SIZE sizeof(Node)
Node* find(Node* h,T d);
//创建一个节点
Node* creat_node(T d)
{
Node* p=malloc(SIZE);
p->data=d;
p->next=NULL;
return p;
}
//创建链表
void creat_list(Node** h)
{
T d;
Node* p=NULL;
Node* pn=NULL;
printf("请输入一个数据:\n");
scanf("%d",&d);
pn=creat_node(d);
*h=pn;//节点类型的指针。
p=*h;
while(1){
printf("请输入一个数据:\n");
scanf("%d",&d);
if(d==0)
break;
pn=creat_node(d);
p->next=pn;
p=p->next;//p指向最后一个节点。
}
}
//遍历链表
void travel(Node* h)
{
printf("list:");
while(h)
{
printf("%5d",h->data);
h=h->next;
}
printf("\n");
}
Node* getpos(Node *h,int n)
{
int i;
if(h==NULL)
return NULL;
for(i-0;i<n-1;i++)
{
h=h->next;
if(h==NULL)
break;
}
return h;
}
//增
int add(Node* h,T d)
{
Node* pn=creat_node(d);
Node* p=h;
while(p->next)
{
p=p->next;
}
p->next=pn;
}
//插入
int Insert(Node** h,int n,T d)
{
if(n<1 || *h==NULL) return 0;
Node* pn=creat_node(d);
if(n==1)
{
pn->next=*h;
*h=pn;
return 1;
}
else
{
Node* pi=getpos(*h,n-1);
pn->next=pi->next;
pi->next=pn;
return 1;
}
}
//找到数据为d的节点并返回其地址,返回NULL表示失败
Node* find(Node* h,T d)
{
while(h)
{
if(h->data==d)
{
return h;
}
h=h->next;
}
return NULL;
}
//删除
int delete_node(Node** h,int n)
{
if(*h==NULL)
{
printf("没有节点可以删除!\n");
return 0;
}
if((*h)->next==NULL)
printf("只有一个头节点,无法删除!\n");
Node* pd=NULL;
if(n==1)
{
pd=*h;
*h=pd->next;
return 1;
}
if(NULL==getpos(*h,n))
{
printf("找不到该节点!\n");
return 0;
}
Node* pb=getpos(*h,n-1);
pd=pb->next;
pb->next=pd->next;
free(pd);
pd==NULL;
pb==NULL;
return 1;
}
//删除数据为d的节点
int delete_data(Node** h,T d)
{
if(*h==NULL)
{
printf("没有节点可以删除!\n");
return 0;
}
if((*h)->next==NULL)
{
printf("只有一个头节点,无法删除!\n");
return 0;
}
//Node* pb=find(*h,d);//删除掉的节点。
Node* pd=NULL;
Node* pt=(*h)->next;
while(pt)
{
if((pt)->data==d)
pd=pt;
(pt)=(pt)->next;
}
while(pt)
{
if((pt)->next==pd){
(pt)->next=(pd)->next;
break;
}
}
free(pd);
pd==NULL;
free(pt);
pt==NULL;
//pb==NULL;
return 1;
}
//改
int change(Node* h,T d,int n)
{
Node* pc=getpos(h,n);
if(NULL==pc)
{
printf("没有该节点!\n");
return 0;
}
pc->data=d;
return 1;
}
int main()
{
Node* head = NULL;
creat_list(&head);//创建链表
add(head,1000);
travel(head);
//printf("%p\n",head->next);
Node* p=find(head,1);
printf("%p\n",p);
Insert(&head,2,888);
travel(head);
delete_node(&head,1);
travel(head);
delete_data(&head,3);11
travel(head);
return 0;
}
单链表的操作
最新推荐文章于 2023-03-16 22:12:32 发布