1.链表的定义
2.链表的初始化
3.链表元素增删改查
#include<stdio.h>
#include <stdlib.h>
#include <time.h>
typedef int ElemType;
typedef struct Node
{
ElemType data;
struct Node* next;
}Node;
typedef struct Node* LinkList;
int getElem(LinkList L,int i){//根据序号查找元素
int j;
LinkList p;
p = L->next;
j = 1;
while(p && j<i)
{
p = p->next;
++j;
}
if(!p || j>i)
return -1;
else
return p->data;
}
int list_insert(LinkList *L,int i,ElemType e){//插入
int j;
LinkList p,s;
p=*L;
j=1;
while(p&&j<i)
{
p=p->next;
++j;
}
if(!p||j>i)
return -1;
else{
s = (LinkList)malloc(sizeof(Node));
s->data =e;
s->next = p->next;
p->next =s;
return 1;}
}
int list_delete(LinkList *L,int i){//删除
int j;
int key;
LinkList p,q;
p =*L;
j =1;
while(p->next&&j<i)
{
p = p->next;
++j;
}
if(!(p->next)||j>i)
return -1;
q = p->next;
p->next =q->next;
key = q->data;
free(q);
return key;
}
void list_createHead(LinkList *L,int n){//头插法
LinkList p;
int i;
srand(time(0));
*L=(LinkList)malloc(sizeof(Node));
(*L)->next =NULL;
for(i=0;i<n;i++){
p=(LinkList)malloc(sizeof(Node));
p->data =rand()%100+1;
p->next = (*L)->next;
(*L)->next =p;
}
}
void list_createTail(LinkList *L,int n){//尾插法
LinkList p,r;
int i;
srand(time(0));
*L=(LinkList)malloc(sizeof(Node));
r=*L;
for(i=0;i<n;i++){
p =(Node *)malloc(sizeof(Node));
p->data =rand()%100+1;
r->next=p;
r=p;
}
r->next =NULL;
}
void list_print(LinkList L){//打印链表
LinkList p = L->next; //将头节点的指针给予临时节点p
while(NULL != p) //节点p不为空,循环
{
printf("%d ",p->data);
p = p->next;
}
printf("\n");
}
int main(){
int x = 0;
int y = 0;
LinkList L;
list_createTail(&L,10);
printf("尾插法:");
list_print(L);
y = list_delete(&L,5);
printf("删除的元素为:%d \n",y);
printf("删除后:");
list_print(L);
list_createHead(&L,10);
printf("头插法:");
list_print(L);
x = getElem(L, 3);
printf("第三个数是:%d \n",x);
list_insert(&L,6,100);
printf("第六位插入数字100:\n");
list_print(L);
return 0;
}