心如止水
Je n'ai pas le temps
posts - 400,comments - 130,trackbacks - 0
很久就知道链表可以用数组来模拟(其实很多数据结构数组都可以实现),一开始感觉用数组模拟还不简单吗?于是很长的一段时间内都没有去写这个程序。今天突然想到了,想去实现它,结果竟然思考了大概20min才想起如何构造数据结构,看来程序还得多动手实践。
以下是我的代码:
insert(a,b):在链表中值为b的元素前面插入a,如果找不到b,将a插入链表末端;
print():遍历整个链表,并输出。
#include<stdio.h>
#include
<string.h>
#define maxn 1007
long n,a[maxn],next[maxn];
void insert(long x,long y)
{
    
long p=0;
    n
++;a[n]=x;
    
while(next[p]&&a[next[p]]!=y)
      p
=next[p];
    next[n]
=next[p];
    next[p]
=n;
}
void print()
{
    
long p=next[0];
    
bool first=true;
    
while(p)
    {
       
if(first) first=false;
       
else printf(" ");
       printf(
"%ld",a[p]);
       p
=next[p];
    }
}
int main()
{
    freopen(
"data.in","r",stdin);
    freopen(
"data.out","w",stdout);
    
long m,a,b;
    
char cmd[maxn];
    n
=0;
    memset(next,
0,sizeof(next));
    scanf(
"%ld",&m);
    
while(m--)
    {
       scanf(
"%s",cmd);
       
if(cmd[0]=='I')
       {
          scanf(
"%ld%ld",&a,&b);
          insert(a,b);
       }
       
else
       {
          print();putchar(
'\n');
       }
    }
return 0;
}


posted on 2010-03-16 22:39 lee1r 阅读(1838) 评论(0)  编辑 收藏 引用 所属分类: 算法与数据结构

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理