单链表相关操作

//2018年07月30日
//@@代码能改变世界吗
//欢迎大家指正错误~~~~~~~~!
#include<iostream>
using namespace std;
typedef struct node{
int data;
struct node *next;
}Lnode,*LinkList;
LinkList listcreat1(LinkList& L) //尾插法建立链表
{
L = (LinkList)malloc(sizeof(Lnode));
Lnode*s, *p = L;
int data1;
L->next = NULL; L->data = 111111;
scanf_s("%d",&data1);
while (data1!=99999)
{
s = (LinkList)malloc(sizeof(Lnode));
s->data = data1;
p->next = s;
s->next = NULL;
p = s;
scanf_s("%d", &data1);
}
return L;
}
LinkList listcreat2(LinkList L){ //用头插法建立链表
L = (LinkList)malloc(sizeof(Lnode));
L->data = 111111; L->next = NULL;
int data1;
LinkList p;
scanf_s("%d",&data1);
while (data1!=99999)
{
p = (LinkList)malloc(sizeof(Lnode));
p->data = data1; p->next = NULL;
p->next = L->next;
L->next = p;
scanf_s("%d", &data1);
}
return L;
}
//按序号查找结点值
LinkList getElem(LinkList L,int i)
{
int flag = 0;
LinkList f=L;
if (i < 0)return NULL;
if (i == 1)return L;
while (f&&flag != i)
{
f = f->next;
flag++;
}
return f;
}
//按值查找结点值
LinkList getELem(LinkList L,int item)
{
LinkList f = L;
while (f->data != item&&f != NULL)
f = f->next;
return f;
}
//插入节点操作
void ElemInsert(LinkList L,int i)
{
LinkList qq,c = L;
int flag = 0;
qq = (LinkList)malloc(sizeof(Lnode));
cout << "请输入插入点的数据:" << endl;
scanf_s("%d",&qq->data);
if (i <=0)cout << "插入位置有误!";
else
{
while (flag != i-1) //建立链表的时候应该记录元素个数以防止插入位置为后边的非法位置
{
c = c->next;
flag++;
}
cout << "前驱节点数据为:"<<c->data << endl; //c为插入位置的前驱节点
qq->next = c->next;
c->next = qq;
}
}
void ElemDelete(LinkList L,int i)
{
int flag = 0;
if (i <= 0)cout << "删除节点位置有误!";
else{
LinkList d,c = L;
while (flag != i - 1) //建立链表的时候应该记录元素个数以防止插入位置为后边的非法位置
{
c = c->next;
flag++;
}
cout << "前驱节点数据为:" << c->data << endl;
d = c->next;
c->next = d->next;
free(d);
}
}

int main(){
LinkList start;
LinkList zflag;
start = listcreat1(start); zflag = start;
while (zflag)
{
cout << zflag->data<<" ";
zflag = zflag->next;
}
ElemInsert(start,5);
cout << endl;
zflag = start;
while (zflag)
{
cout << zflag->data << " ";
zflag = zflag->next;
}
ElemDelete(start,5);
zflag = start;
cout << endl;
zflag = start;
while (zflag)
{
cout << zflag->data << " ";
zflag = zflag->next;
}
return 0;
}

posted @ 2018-08-01 16:43  代码拯救世界可以吗  阅读(103)  评论(0编辑  收藏  举报