您的位置:首页 > 其它

链表的基本操作

2014-04-09 15:57 218 查看
RT。题目地址http://zju.acmclub.com/index.php?app=problem_title&id=1&problem_id=1326

包含链表的插入、删除、创建等基本操作。

代码:

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

typedef struct Node
{
int data;
struct Node *next;
} Node,*Linklist;//定义结点
int main()
{

int n1,buf,n2,num,a,e;//n1为初始链表的长度,n2为操作的数量
char str[10];
cin>>n1;

Node *L,*s;
//cout<<"n1="<<n1<<endl;
//初始化头结点
L = (Linklist)malloc(sizeof(Node));
L->next = NULL;
while(n1--)
{
//尾插法初始化链表
cin>>buf;
s = (Node*)malloc(sizeof(Node));//创建新结点
s->data = buf;
s->next = L->next;
L->next = s;

}
cin>>n2;
while(n2--)
{
cin>>str;//str为命令字符串
if(strcmp(str,"show") == 0)
{
Node *p = L->next;//设置工作指针
if(p == NULL)
cout<<"Link list is empty"<<endl;
else
{
while(p->next != NULL)
{
cout<<p->data<<" ";
p = p->next;
}
cout<<p->data<<endl;

}

}
else if(strcmp(str,"delete")==0)
{
cin>>a;
int count = 1;//计数,初始为1
Node *pre = L;
Node *p = L->next;
Node *q;

if(a<1)
cout<<"delete fail"<<endl;
while(p!=NULL && count < a)
{
pre = p;
p = p->next;
count++;
}
if(p != NULL)
{
q = p;
p = p->next;
pre->next = p;
cout<<"delete OK"<<endl;
}
else
cout<<"delete fail"<<endl;

}
else if (strcmp(str,"get")==0)
{
cin>>a;
int count = 1;
Node *p = L->next;
while(p!=NULL && count < a)
{
p = p->next;
count++;
}
if(p == NULL)
cout<<"get fail"<<endl;
else
cout<<p->data<<endl;

}
else if(strcmp(str,"insert")==0)
{
cin>>a>>e;
if(a<1)
cout<<"insert fail"<<endl;
int count = 1;
Node *pre = L;
Node *p = L->next;
if(p == NULL && count == a)//特殊情况,空表时插入
{
Node *s = (Node*)malloc(sizeof(Node));
s->data = e;
s->next = p;
pre->next = s;
cout<<"insert OK"<<endl;
}
else
{
//普通情况的插入,若a=3,实际上由于count的限制pre和p只向后移动2次。。
while(p!=NULL && count < a)
{
pre = p;
p = p->next;
count++;
}
if(p!=NULL)
{
Node *s = (Node*)malloc(sizeof(Node));
s->data = e;
s->next = p;
pre->next = s;
cout<<"insert OK"<<endl;
}
else
cout<<"insert fail"<<endl;
}

}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: