您的位置:首页 > 编程语言 > C语言/C++

C++单链表的实现

2012-05-12 13:57 337 查看
最近想要找个实习,数据结构的基础太差,所以复习了一下。。下面是用C++实现的单链表。

linklist.cpp

/*
* linklist.cpp
*
*  Created on: 2012-5-12
*      Author: awind
*/

#include <iostream>
#include <cstdlib>
using namespace std;

typedef struct LNode{
int data;
struct LNode *next;
}LNode,*LinkList;

void CreateList_L(LinkList &L,int n)  //创建一个长度为n的单链表
{
LNode *p;
L=new LNode;
L->next=NULL;

for(int i=0;i<n;++i)
{
cout<<"please input the data of each LinkList node(0 to end): "<<endl;
p=new LNode;  //新建个新节点
cin>>p->data;

p->next=L->next;  //将p节点插入L后方
L->next=p;  //p变为头结点

}
}

bool GetElem_L(LinkList &L,int i,int &e) //获取单链表的第i个值,并由e返回其值
{
LNode *p;
p=L->next;
int count=1; //计数
while(p&&count<i)
{
p=p->next;
++count;
}
if(!p||count>i)
return false;
e=p->data;
return true;
}

bool ListInsert_L(LinkList &L,int i,int e) //在含有头结点的单链表的i位置插入元素e
{
LNode *p;
p=L;
int count=0;
while(p&&count<i-1)
{
p=p->next;
++count;
}
if(!p||count>i-1)
return false;
LNode *newNode=new LNode;
newNode->next=p->next;
p->next=newNode;
newNode->data=e;
return true;
}

bool ListDelete_L(LinkList &L,int i,int &e) //删除第i个节点 并由e返回其值
{
LNode *p;
p=L;
int count=0;
while(p&&count<i-1){
p=p->next;
++count;
}
if(!p||count>i-1)
return false;
//删除结点
LNode *q=new LNode;
q=p->next;
p->next=q->next;
q->next=NULL;
e=q->data;
delete q;
return true;
}

void MergeList_L(LinkList &La,LinkList &Lb,LinkList &Lc)  //归并链表La和Lb得到新的单链表Lc,Lc的元素也按值非递减排列
{
LNode *pa=new LNode;
LNode *pb=new LNode;
LNode *pc=new LNode;
pa=La->next;
pb=La->next;
Lc=pc=La;

while(pa&&pb)
{
if(pa->data<=pb->data){
pc->next=pa;
pc=pa;
pa=pa->next;
}else{
pc->next=pb;
pc=pb;
pb=pb->next;
}
pc->next=pa?pa:pb;
delete Lb;

}
}

void PrintList_L(LinkList L)  //打印出所有节点
{
cout<<"print the LinkList: "<<endl;
LNode *p=L->next;

int count=0;
while(p){
cout<<p->data<<" ";
++count;
p=p->next;
if(count%5==0)
cout<<"\n";

}
cout<<"\nend of LinkList."<<endl;
}

int SearchElem_L(LinkList &L,int e) //查找元素e 返回位置
{
LNode *p=L->next;
int count=0;
while(p&&p->data!=e)
{
p=p->next;
++count;
}
if(!p){
cout<<"can't find the element!"<<endl;
return 0;}
return count;
}

int main()
{
int n,searchElem,insertElem,pos,delPos,e;
cout<<"input the number of node ";
cin>>n;
LinkList linkList;
CreateList_L(linkList,n);
PrintList_L(linkList);

cout<<"input the number you want to search: ";
cin>>searchElem;
int elementPos=SearchElem_L(linkList,searchElem);
cout<<"the element is in the "<<elementPos<<" position."<<endl;
cout<<"input the element you want to insert(pos and data)";
cin>>pos>>insertElem;
ListInsert_L(linkList,pos,insertElem);

cout<<"after the insert: "<<endl;
PrintList_L(linkList);
cout<<"\n";

cout<<"input the pos you want to del: ";
cin>>delPos;
ListDelete_L(linkList,delPos,e);
cout<<"after the del: "<<endl;
PrintList_L(linkList);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 C++