#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//定义结构体
struct List
{
int data;
struct List* next;
};
//输入空表
void init(struct List** phead)
{
*phead=NULL;
}
//求表长
int getLength(struct List* head)
{
int len=0;
while(head){
len++;
head=head->next;
}
return len;
}
//输出链表
void printList(struct List* head)
{
while(head){
printf("%d ",head->data);
head=head->next;
}
putchar('\n');
}
//创建节点
struct List* creatList(int x)
{
struct List* t;
t=(struct List*)malloc(sizeof(struct List));
t->next=NULL;
t->data=x;
return t;
};
//查找第K项
struct List* findKth(struct List*head, int k)
{
int count=1;
struct List* p;
p=head;
while(p && count<k){
p=p->next;
count++;
}
return p;
};
//插入
int insert(struct List** phead, int k, int x)
{
if(k<1)
return 0;
else if(k==1){
struct List* t;
t=creatList(x);
t->next=*phead;
*phead=t;
return 1;
}
else{
struct List* p;
p=findKth(*phead, k-1); //找到插入位置的前一项
if(p){
struct List* t;
t=creatList(x);
t->next=p->next;
p->next=t;
return 1;
}
else
return 0;
}
}
//删除
int removeList(struct List** phead, int k, int* px)
{
if(k<1)
return 0;
else if(k==1){
if(*phead){
*px=(*phead)->data;
*phead=(*phead)->next;
return 1;
}
else
return 0;
}
else{
struct List* p;
p=findKth(*phead, k-1);
if(p==NULL || p->next==NULL)
return 0;
struct List* t;
t=p->next;
p->next=t->next;
*px=t->data;
free(t);
return 1;
}
}
int main()
{
struct List* head;
init(&head);
int k = getLength(head);
insert(&head,1,11);
insert(&head,1,22);
insert(&head,2,33);
insert(&head,4,44);
insert(&head,6,55);
int x;
removeList(&head,1,&x);
printList(head);
return 0;
}
单链表的输出、插入及删除
最新推荐文章于 2024-07-13 16:00:03 发布