包含单链表的建表操作
增 删 查
如果有错误之处,请留言指正。
#include<bits/stdc++.h>
using namespace std;
typedef int ElemType;
typedef struct LNode
{
ElemType data;
struct LNode *next;
} LNode,*LinkList;
/*头插法创建单链表*/
LinkList List_HeadInsert(LinkList &L)
{
LNode *p;
ElemType x;
L=(LinkList)malloc(sizeof(LNode)); //创建头结点并分配空间
L->next = NULL;
int n,i;
cout<<"请输入头插法建表元素个数:";
cin>>n;
for(i=0; i<n; i++)
{
cin>>x;
p = (LNode*)malloc(sizeof(LNode));
p->data = x;
p->next = L->next;
L->next = p;
}
return L;
}
/*尾插法创建单链表*/
LinkList List_TailInsert(LinkList &L)
{
LNode *p;
ElemType x;
// L=(LinkList)malloc(sizeof(LNode)); //创建头结点并分配空间
L = new LNode;
L->next = NULL;
LNode *r = L;
int n,i;
cout<<"请输入尾插法建表元素个数:";
cin>>n;
for(i=0; i<n; i++)
{
cin>>x;
p = (LNode*)malloc(sizeof(LNode));
p->data = x;
r->next = p;
r=p;
}
r->next = NULL;
return L;
}
/*找到第i个位置的结点指针*/
LNode *findLocation(LinkList L,int i)
{
int count=1;
LNode *p = L->next;
if(i == 0)
return L; //若i=0,返回头结点
if(i < 1)
return NULL; //非法参数
while(count<i && p)
{
p=p->next;
count++;
}
return p; //若i大于表长,返回p=null
}
/*按位置插入结点*/
void InsertByLocation(LinkList &L,ElemType x,int Location)
{
LNode *p = findLocation(L,Location-1);
//LNode *q = (LNode*)malloc(sizeof(LNode));
LNode *q = new LNode ;
q->data = x;
q->next = p->next;
p->next = q;
}
/*打印单链表*/
void PrintLinkList(LinkList L)
{
LNode *p=L->next;
cout<<"打印链表如下:"<<endl;
while(p)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
/*删除单链表中某个位置的值*/
void DeleteByValue(LinkList &L,int i)
{
LNode *p = findLocation(L,i-1);
LNode *q=p->next;
p->next=q->next;
delete q;
}
int main()
{
LinkList head;
//List_HeadInsert(head);
List_TailInsert(head);
PrintLinkList(head);
//InsertByLocation(head,3,3);
DeleteByValue(head,3);
PrintLinkList(head);
return 0;
}