编写完整程序LinkList.c或LinkList.cpp实现链表的初始化、查找、插入、删除、遍历等操作。
内容
1.从键盘输入n个整数,产生带头结点的单链表,并输入结点值。
【创建长度为n的链表】【遍历】
2.从键盘输入1个整数x,在单链表中查找x所在的位置。若找到,输出该元素所在的位置;若找不到,则显示“找不到”。【按值查找】
3.从键盘输入2个整数x、i,将元素x插入到第i个元素处,插入操作结束后遍历链表,观察输出结果。【按序号查找】【插入】
4.从键盘输入1个整数,表示删除第之个元素,删除操作结束后遍历链表,观察输出结果。【按序号查找】【删除】
5.查看当前单链表的长度。【求链表的长度】
代码实现
#include<iostream>
#include<assert.h>
using namespace std;
#define datatype int
typedef struct Inode
{
datatype data;
struct Inode* next;
struct Inode* pre;
struct Inode* head;
struct Inode* present;//当前
void Creat();
void Input();
void Output();
bool Check(); //按值查找
bool Insert() ;//按序号查找 插入
bool Delete();
int Length();//求表长
}LNode;
void LNode::Creat()
{
present = (LNode*)malloc(sizeof(LNode));
head = present;
present->next = NULL;
present->pre = NULL;
}
void LNode::Input()
{
int n;
cout<<"个数:";
cin>>n;
cout<<"输入元素:";
for(int i=0;i<n;i++)
{
present = (LNode*)malloc(sizeof(LNode));
head->pre = present;
present->next = head;
head = present;
//相当于头插
present->pre = NULL;
cin>>present->data;
}
}
bool LNode::Check()
{
present = head;
int x,i=1;
cout<<"输入你想查找的元素: ";
cin>>x;
while(present->next !=NULL)
{
if(x==present->data)
{
cout<<"元素在第"<<i<<"个"<<endl;
return true;
}
else
{
present = present->next;
i++;
}
}
cout<<"找不到!"<<endl;
return false;
}
void LNode::Output()
{
present=head;
while(present->next!=NULL)
{
cout<<present->data<<" ";
present=present->next;
}
if(head->next==NULL)
{
cout<<"表中无数据!"<<endl;
}
cout<<endl;
}
bool LNode::Insert()
{
datatype x;
int i;
cout<<"输入x,i,将x插入第i个元素的位置: ";
cin>>x>>i;
if (i<0)
{
return false;
}
else if(present==NULL)
{return false;}//i值不合法
present=head;
int j=0;
while(present!=NULL&&j<i-2)//循环找到第i-2个结点
{
present=present->next;
j++;
}
if((i-2)>(-1))//插入表中
{
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = x; //将数据元素e存入x数据域中
s->next = present->next; //令s指向p结点的后继结点。
present->next = s;
}
if((i-2)==(-1))//插入表头
{
LNode *s = (LNode *)malloc(sizeof(LNode));
s->data = x;
head->pre = s;
s->next = head;
head = s;
//相当于头插
s->pre = NULL;
}
return true;
}
bool LNode::Delete()
{
int i;
cout<<"输入i,删除第i个元素: ";
cin>>i;
if (i<0)
{return false;}
else if(present==NULL)
{return false;}//i值不合法
present=head;
int j=0;
while(present!=NULL&&j<i-1)//循环找到第i-2个结点
{
present=present->next;
j++;
}
if (present->pre == NULL)
{
//头指针与当前指针指向同一个,将头指针给下一个
head = present->next;
delete present;
}
else if (present->pre != NULL)
{
present->pre->next = present->next;
present->next->pre = present->pre;
delete present;
}
return true;
}
int LNode::Length()
{
present=head;
int len=0;
while(present->next != NULL)
{
present=present->next;
len++;
}
return len;
}
int main()
{
LNode L;
L.Creat();
L.Input();
L.Output();
L.Check();
L.Insert();
L.Output();
L.Delete();
L.Output();
cout<<"查看当前链表的长度:"<<L.Length()<<endl;
return 0;
}