#include<iostream>
using namespace std;
typedef struct LNode {
int data;
struct LNode* next;
}LNode,*LinkList;
//带头结点头插法
LinkList HeadInSert(LinkList& L)
{
LNode* p;
int x;
cin >> x;
L = (LinkList)malloc(sizeof(LNode));
L->next = NULL;
while (x != 9999)
{
p = (LinkList)malloc(sizeof(LNode));
p->data = x;
p->next = L->next;
L->next = p;
cin >> x;
}
return L;
}
//不带头结点头插法
LinkList NoHeadInsert(LinkList& L)
{
LNode* p;
int x;
L = (LinkList)malloc(sizeof(LNode));//建立一个普通的结点,data赋值
L->next = NULL;
cin >> x;
L->data = x;
while(x != 9999)
{
cin >> x;
p = (LinkList)malloc(sizeof(LNode));
p->data = x;
p->next = L;
L = p;
}
return L;
}
//尾插法
LinkList TailInsert(LinkList& L)
{
LNode* r, * p;
L = (LinkList)malloc(sizeof(LNode));
int x;
r = L;
cin >> x;
while (x != 9999)
{
p = (LinkList)malloc(sizeof(LNode));
p->data = x;
r->next = p;
r = p;
cin >> x;
}
r->next = NULL;
return L;
}
void ShowList(LinkList& L)
{
LNode* p;
p = L->next;
while (p)
{
cout << p->data <<' ';
p = p->next;
}
cout << endl;
}
LinkList GetElem(LinkList& L, int i)
{
LNode* p;
int j = 1;
p = L->next;
if (i == 0)
return L;
if (i < 1)
return NULL;
if (p && j < i)
{
p = p->next;
j++;
}
return p;
}
LinkList InsertList(LinkList& L, int i)
{
LNode* p, * s;
int x;
cin >> x;
p = GetElem(L, i - 1);
s = (LinkList)malloc(sizeof(LNode));
s->data = x;
s->next = p->next;
p->next = s;
return L;
}
LinkList DeleteList(LinkList& L, int i)
{
LNode* p, * s;
p = GetElem(L, i - 1);
s = p->next;
p->next = s->next;
free(s);
return L;
}
int main()
{
LinkList L;
HeadInSert(L);
/*NoHeadInsert(L);
TailInsert(L);*/
ShowList(L);
int i;
cin >> i;
/*InsertList(L, i);
ShowList(L);*/
DeleteList(L, i);
ShowList(L);
return 0;
}
链表基本操作
最新推荐文章于 2024-10-31 13:56:46 发布