| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 711 人关注过本帖, 1 人收藏
标题:数据结构试验——链表
只看楼主 加入收藏
晓婷长月
Rank: 1
等 级:新手上路
帖 子:61
专家分:0
注 册:2013-6-4
收藏(1)
 问题点数:0 回复次数:1 
数据结构试验——链表
数据结构试验——链表
程序代码:
#include<iostream>
using namespace std;
typedef int Elemtype;
typedef struct LNode
{
    Elemtype data;
    struct LNode *next;
}LNode,*Linklist;
void initlist(Linklist *L)
{
    *L=(LNode *)malloc(sizeof(LNode));
    (*L)->next=NULL;
    cout<<"初始化成功!\n";
}
int Getlen(Linklist L)
{
    int num=0;
    LNode *p;
    p=L->next;
    while(p!=NULL)
    {
        num++;
        p=p->next;
    }
    return (num);
}
void Inselem(Linklist L,int i,Elemtype x)
{
    LNode *p,*q,*s;
    int pos=1;
    p=L;
    if(i<1 || i>Getlen(L)+1) exit(1);
    s=(LNode *)malloc(sizeof(LNode));
    s->data=x;
    while(pos<=i)
    {
        q=p;
        p=p->next;
        pos++;
    }
    s->next=q->next;
    q->next=s;
}
void displist(Linklist L)
{
    LNode *p;
    p=L->next;
    while(p!=NULL)
    {
        cout<<p->data<<' ';
        p=p->next;
    }
     printf("\n");
}
LNode *Getelem(Linklist L,int i)
{
    LNode *p;int pos=1;
    p=L->next;
    if(i<1 || i>Getlen(L)) exit (1);
    while(pos<i)
    {
        p=p->next;
        pos++;
    }
    return p;
}
LNode *Locate(Linklist L,Elemtype x)
{
    LNode *p;
    p=L->next;
    while(p!=NULL && p->data!=x)
        p=p->next;
    return p;
}
void Delelem(Linklist L,int i)
{
    int pos=1;
    LNode *q=L,*p;
    if(i<1 || i>Getlen(L)) exit(1);
    while(pos<i)
    {
        q=q->next;
        pos++;
    }
    p=q->next;
    q->next=p->next;
    free(p);
    cout<<"元素已成功删除!\n";
}
int main()
{
    Linklist l;
    initlist(&l);
    int n,j;
    Elemtype a;
    cout<<"请输入需要定义的结点的个数n:";
    cin>>n;
    for(int i=1;i<=n;i++)
    {  
        cout<<"请输入要插入的序号及元素:";
        cin>>j>>a;
        if(j<1 || j>n+1) break;
        Inselem(l,j,a);
    }
    cout<<"链表元素为:";
    displist(l);
    cout<<"\n线性表的长度为:"<<Getlen(l)<<endl;
    cout<<"请输入要取元素的序号j:";
    cin>>j;
    cout<<"所取的元素为:"<<Getelem(l,j)->data<<endl;
    cout<<"请输入需要查找的元素:";
    cin>>a;
    cout<<"所查找的元素的序号为:"<<Getlen(l)-Getlen(Locate(l,a))<<endl;
    cout<<"请输入要删除的元素的序号:";
    cin>>j;
    Delelem(l,j);

    return 0;
}


2013-06-16 02:59
晓婷长月
Rank: 1
等 级:新手上路
帖 子:61
专家分:0
注 册:2013-6-4
收藏
得分:0 
全部资料文件

链表.rar (1.25 KB)
2013-06-16 02:59
快速回复:数据结构试验——链表
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.016474 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved