链式存储线性表时,不需要使用地址连续的存储单元。
方法:function.cpp
#include"head.h"
#include<malloc.h>
#include<stdio.h>
LinkList CreatList1(LinkList &L){//创建链表
LNode *s;
int x;
L=(LinkList)malloc(sizeof(LNode));
L->next=NULL;
scanf("%d",&x);
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
s->next=L->next;//利用头插法创建链表
L->next=s;
scanf("%d",&x);
}
return L;
}
LinkList CreatList2(LinkList &L){//利用尾插法创建链表
int x;
L=(LinkList)malloc(sizeof(LNode));
LNode *s,*r;//r是指向尾结点指针
r=L;
scanf("%d",&x);
while(x!=999){
s=(LNode*)malloc(sizeof(LNode));
s->data=x;
r->next=s;
s->next=NULL;
r=s;//尾指针指向尾结点
scanf("%d",&x);
}
r->next=NULL;
return L;
}
//按位置查找
LNode *GetElem(LinkList L,int i){//获取链表中第i个结点
int count=0;
LNode *p=L;
if(i==0) return L;
if(i<0) return NULL;
while(p&&count<i){
p=p->next;
count++;
}
return p;
}
//按位置查找
LNode *LocateElem(LinkList L,ElemType e){
if(L->next==NULL) return NULL;
LNode *p=L->next;
while(p&&p->data!=e){
p=p->next;
}
return p;
}
//插入结点
LinkList InsertList(LinkList &L,int i,ElemType e){//在第i个位置上插入结点
LNode *p,*s;
p=L;
s=(LNode*)malloc(sizeof(LNode));
s->data=e;
int count=0;
while(p&&count<i-1){
p=p->next;
count++;
}
s->next=p->next;
p->next=s;
return L;
}
//删除结点
LinkList DeleteList(LinkList &L,int i){//删除第i个结点
LNode *p=L,*q;
int count=0;
while(p&&count<i-1){
p=p->next;
count++;
}
q=p->next;
p->next=q->next;
//free(p);
return L;
}
//遍历所有结点
void PrintList(LinkList &L){
LNode *p=L->next;
while(p){
printf("%d ",p->data);
p=p->next;
}
}
头文件:head.h
typedef int ElemType;
typedef struct LNode{//定义结点
ElemType data;
struct LNode *next;
}LNode,*LinkList;
LinkList CreatList1(LinkList &L);//头插法创建链表
LinkList CreatList2(LinkList &L);//尾插法创建链表
LNode *GetElem(LinkList L,int i);//获取第i位置的元素
LNode *LocateElem(LinkList L,ElemType e);//按值查找某个元素
LinkList InsertList(LinkList &L,int i,ElemType e);//在第i个位置上插入结点
LinkList DeleteList(LinkList &L,int i);//删除某个结点
void PrintList(LinkList &L);//遍历所有结点
主函数:main.cpp
#include<iostream>
#include"head.h"
using namespace std;
int main(){
LinkList list;
//CreatList1(list);//利用头插法实现
CreatList2(list);//利用尾插法实现
LNode *node=GetElem(list,1);
printf("第一个结点是:",node->data);
LNode *node1=LocateElem(list,3);
printf("\n寻找链表中值为3的结点:%d",node1->data);
printf("\n在第二结点处插入7");
InsertList(list,2,7);
LNode *node2=GetElem(list,2);
printf("\n第二个结点处的值为:%d\n",node2->data);
DeleteList(list,2);
LNode *node3=GetElem(list,2);
printf("第二个位置元素值为:%d\n",node3->data);
PrintList(list);
return 0;
}