#include <stdio.h>
#include <stdbool.h>
#include <malloc.h>
typedef int ElemType;
typedef struct Lnode {
ElemType data;
struct Lnode *next;
}Lnode, *Linklist;
//初始化链表
Linklist InitList(){
Linklist L=(Linklist)malloc(sizeof (Linklist));
L->next=NULL;
return L;
}
//创造节点
Lnode * createNote(int e)
{
Lnode* newnode=(Lnode *) malloc (sizeof (Lnode)) ;
if(newnode == NULL){
return NULL;
}
newnode->data=e;
newnode->next=NULL;
return newnode;
}
//长度
int Length(Linklist L){
int length=1;
Lnode *p =L->next;
while (p->next!=NULL)
{
p=p->next;
length++;
}
return length;
}
//按序查找
Lnode* GetElem(Linklist L, int i){
Lnode *p =L;
int j=0;
if(i<0||i>Length(L))
{
return 0;
}
while ( p!=NULL&&j<i){
p=p->next;
j++;
}
return p;
}
//按位查找
Lnode* LocateElem(Linklist L, ElemType data){
Lnode *p =L->next;
while ( p!=NULL && p->data!=data){
p=p->next;
}
return p;
}
//头插法
bool listHeadInsert (Linklist L, ElemType data)
{
Lnode * newnode= createNote(data);
newnode->next=L->next;
L->next=newnode;
return true;
}
//尾插法
bool listTailInsert (Linklist L, ElemType data)
{
Lnode* newnode= createNote(data);
Lnode* lastnode= GetElem(L,Length(L));
lastnode->next=newnode;
newnode->next=NULL;
return true;
}
//按序插入
bool ListInsert (Linklist L, int i, ElemType data){
if(i<0||i>Length(L))
{
return false;
}
Lnode * newnode = createNote(data);
Lnode * tempnode= GetElem(L,i-1);
newnode->next=tempnode->next;
tempnode->next=newnode;
return true;
}
//按序删除节点
Lnode * ElemDelete(Linklist L,int i){
Lnode* tempnoode= GetElem(L,i-1);
Lnode *p =tempnoode->next;
tempnoode->next=p->next;
free(p);
return p;
}
//按位删除
bool LocateElemDelete(Linklist L,int i) {
Lnode *p = GetElem(L, i);
Lnode *q = p->next;
p->data = q->data;
p->next = q->next;
free(q);
}
//打印
void Listprint(Linklist L){
Lnode *p=L->next;
while (p!=NULL){
printf("%d ",p->data);
p=p->next;
}
printf("\n");
}
int main() {
Linklist linklist;
linklist=InitList();
listHeadInsert(linklist,1);
listHeadInsert(linklist,2);
listHeadInsert(linklist,3);
listHeadInsert(linklist,4);
listHeadInsert(linklist,5);
listHeadInsert(linklist,6);
listTailInsert(linklist,11);
listTailInsert(linklist,22);
listTailInsert(linklist,33);
listTailInsert(linklist,44);
listTailInsert(linklist,55);
listTailInsert(linklist,66);
Listprint(linklist);
printf( "%d\n", Length(linklist));
ListInsert(linklist,3,666);
ListInsert(linklist,1,88888);
Listprint(linklist);
printf( "%d\n", Length(linklist));
ElemDelete(linklist,1);
Listprint(linklist);
printf( "%d\n", Length(linklist));
printf( "%d\n", GetElem(linklist,2)->data);
return 0;
}
c语言实现链表
最新推荐文章于 2024-08-30 14:17:16 发布