单链表是学习数据结构的基础,一些简单的操作还是要熟练掌握
头文件list.h
//list.h
#include "stdio.h"
#include "stdlib.h"
#include "malloc.h"
#include
using namespace std;
//定义节点结构体
typedef struct LNode
{
int data;
struct LNode * next;
}LNode,*LinkList;
//函数声明
LinkList LinkListInit();
void showmeu();
void CreateList(LNode *);
void printList(LNode *);
void addNode(LNode *);
void deleteNode(LNode *);
void searchNode(LNode *);
void reverList(LNode *);
void select(LNode *);
源文件
//list.cpp
#include "list.h"
//list practice
//main函数
int main()
{
LinkList head=LinkListInit();
select(head);
return 0;
}
//链表初始化
LinkList LinkListInit()
{
LinkList pHead;
pHead=(LinkList)malloc(sizeof(LNode));
if(pHead==NULL)
{
cout<
exit(-1);
}
//初始化成功
cout<
pHead->next=NULL;
return pHead;
}
void showmeu()
{
cout<
cout<
cout<
cout<
cout<
cout<
cout<
cout<
cout<
}
void select(LNode *head)
{
int selection;
while(1)
{
// system("cls");//清屏
showmeu();
cout<
cin>>selection;
switch(selection)
{
case 1:
CreateList(head);break;
case 2:
printList(head);break;
case 3:
addNode(head);break;
case 4:
deleteNode(head);break;
case 5:
searchNode(head);break;
case 6:
reverList(head);break;
case 7:
exit(-1);
}
}
}
//创建链表
void CreateList(LNode * head)
{
int n;
int x;
LinkList p=head;
cout<
cin>>n;
if(n<=0)
exit(-1);
for(int i=1;i<=n;i++)
{
LinkList q=(LinkList )malloc(sizeof(LNode));
cout<
cin>>x;
q->data=x;
q->next=NULL;
//关键的两句,用尾插法
p->next=q;
p=q;
}
cout<
}
//遍历链表
void printList(LNode * head)
{
LinkList p=head->next;
if(p==NULL)
cout<
cout<
while(p!=NULL)
{
cout<data<
p=p->next;
}
}
int getlistlong(LNode * head)
{
LinkList p=head->next;
int n=0;
if(p==NULL)
return 0;
while(p!=NULL)
{
n++;
p=p->next;
}
return n;
}
//插入节点
void addNode(LNode * head)
{
int n;
int x;
int length=getlistlong(head);
if(head==NULL)
cout<
else
{
cout<
cin>>n;
if(n>length)
{ cout<
n=length+1;
}
if(n<=0)
cout<
cout<
cin>>x;
LinkList p=(LinkList)malloc(sizeof(LNode));
p->data=x;
LinkList q=head;
for(int i=1;i
{
q=q->next;
}
p->next=q->next;
q->next=p;
cout<
}
}
//删除节点
void deleteNode(LNode * head)
{
LinkList p; //要删除的元素
int n;
if(head==NULL || head->next==NULL)
cout<
else
{
cout<
cin>>n;
if(n<=0)
cout<
else
{
LinkList q=head;
for(int i=1;i
{
q=q->next;
}
p=q->next;
q->next=q->next->next;
cout<data<
}
}
}
//查找节点
void searchNode(LNode * head)
{
LinkList p=head;
int n=0;
int x;
cout<
cin>>x;
if(head==NULL || head->next==NULL) //若头节点为空,或后面也指向一个空的节点
cout<
else
{
while(p->next!=NULL)
{
if(p->data==x)
{
cout<
break;
}
else
{
p=p->next;
n++;
}
if(p==NULL)
cout<
}
}
}
//链表逆序
void reverList(LNode * head)
{
LinkList p=NULL;
LinkList q=NULL;
if(head == NULL)
{
cout<
}
p=head->next;
while(p->next != NULL)
{
q=p->next;
p->next=q->next;
q->next=head->next;
head->next=q;
}
cout<
printList(head);
}
运行结果: