// Liner linked list.cpp : Defines the entry point for the console application.
/*-----CODE FOR FUN---------------
-------CREATED BY Dream_Whui--
-------2015-1-20--------------------*/
#include "stdafx.h"
#include <iostream>
using namespace std;
#define ElemType char
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define INFEASIBLE -1
typedef struct LNode//定义线性链表的结果
{
ElemType data;
LNode *next;
}LNode,*LinkList;
void CreateList(LinkList &L , int n)//创建长度为n的线性链表
{
char e;
L =(LinkList)malloc(sizeof(LNode));
L->next = NULL;
for(int k=n; k>0; --k)
{
cin>>e;
LinkList p = (LinkList)malloc(sizeof(LNode));
p->data = e;
p->next = L->next;
L->next = p;
}
}
int ListInsert(LinkList &L, int i , ElemType e)//在第i个结点前(第i-1个结点后面)插入元素e
{
LinkList p = L;
int j=0;
while(p && j<i-1)//找到第i-1个结点
{
p = p->next;
j++;
}
if(!p || j>i-1)//位置i<1或者i>表长+1
return ERROR;
LinkList s = (LinkList)malloc(sizeof(LNode));
s->data = e;
s->next = p->next;
p->next = s;
return OK;
}
int ListDelete(LinkList &L, int i, ElemType &e)//删除第i个结点
{
LinkList p = L;
int j =0;
while(p->next && j<i-1)//找到第i-1个结点,p指向它 (i<=表长)
{
p = p->next;
j++;
}
if(!(p->next) || j>i-1)
return ERROR;
LinkList q = p->next;
p->next = q->next;
e = q->data;
free(q);
return OK;
}
int main(int argc, char* argv[])
{
LinkList L;
CreateList(L,5);
LinkList p = L;
while(p->next)
{
cout<<p->next->data<<" ";
p=p->next;
}
cout<<endl;
ListInsert(L,1,'W');
p=L;
while(p->next)
{
cout<<p->next->data<<" ";
p=p->next;
}
cout<<endl;
char e;
ListDelete(L,3,e);
p=L;
while(p->next)
{
cout<<p->next->data<<" ";
p=p->next;
}
cout<<endl;
cout<<"e="<<e<<endl;
return 0;
}数据结构--线性链表
最新推荐文章于 2025-04-19 12:16:06 发布
2085

被折叠的 条评论
为什么被折叠?



