#include <stdio.h >
#include <iostream>
using namespace std;
typedef int DataType;
typedef struct Node
{
DataType data;
struct Node * next;
}Node,*LinkList;
void CreateListH(LinkList &L)//头插法
{
cout<<"请输入数\n";
Node *s;
int c;
L = new Node;
L->next = NULL;
cin>>c;
while (c != 0)
{
s = new Node;
s->data = c;
s-> next = L->next;
L->next = s;
cin>>c;
}
}
void CreateListT(LinkList &L)//尾插法
{
int c;
cout<<"please input\n";
Node *r,*s;
L = new Node;
L->next = NULL;
r = L;
cin >> c;
while(c != 0)
{
s = new Node;
s->data = c;
r->next = s;
r = s;
cin >> c;
}
r->next = NULL;
}
void Output(LinkList L)// l 头结点
{
Node *p;
for(p=L->next;p != NULL;p=p->next)
printf("%d ",p->data);
printf("\n");
}
Node * GetData(LinkList L,int i) //第i个节点的位置
{
int j;
Node *p;
cout << "input第几个节点\n";
cin >> i;
i = i-1;
if (i < 0)
return NULL;
p = L;//p point to head
j = 0;//count++
while (p->next != NULL && j < i)
{
p = p->next;
j++;
}
if (i == j)
return p;
else
return NULL;
}
int Length(LinkList L)//计算长度
{
Node *p;
int len = 0;
p = L->next;
while(p != NULL)
{
p= p->next;
len++;
}
return len;
}
void Delete(LinkList &L,int i)//删除
{
Node *pre,*r;
cout << "please input which node will be deleted\n";
pre = GetData(L,i-1);
if (pre == NULL || pre->next == NULL)
printf("delete is unreasonable\n");
else
{
r = pre->next;
pre->next = r->next;
delete(r);
}
}
void Insert(LinkList &L,int i,DataType x)//在第i个节点前插入x的新节点
{
Node *pre,*s;
cout << "input x (待插入)\n";
cin >> x;
pre = GetData(L,i-1);
if (pre == NULL)
printf("error\n");
else
{
s = new Node;
s->data = x;
s->next = pre->next;
pre->next = s;
}
}
int main()
{
Node *L;
int c,d,x,i;
cout<<"choose way\n";// 头插还是尾插
cin >> c;
if (c == 1)
CreateListH(L);
else
CreateListT(L);
d = Length(L);
cout << d << endl;
Insert(L, i,x);
Output(L);
Delete(L, i);
Output(L);
}
链表的创建等一系列操作
最新推荐文章于 2024-11-14 16:38:00 发布