線性表

線性表的順序實現

找到再補

線性表的鏈式實現

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define ElemType int
#define Status int
#define ListSize 1000
using namespace std;

typedef struct LNode
{
    ElemType data;
    struct LNode *next;
}*LinkList;

Status Init_LinkList(LinkList &L)
{
    L = (LNode *)malloc(sizeof(LNode));
    L->next = NULL;
    return OK;
}

Status Insert_List(LinkList &L,int i,ElemType e)
{
    LinkList p,q;
    int j = 0;
    if(i==1)
    {
        p = (LNode*)malloc(sizeof(LNode));
        p->data = e;
        p->next = L->next;
        L->next = p;
    }
    else
    {
        p = L;
        while(p&&j<i-1)
        {
            p = p->next;
            ++j;
        }
        q = (LNode*)malloc(sizeof(LNode));
        q->next = NULL;
        q->data = e;
        p->next = q;
    }
    return OK;
}

Status List_Traverse(LinkList L)
{
    LinkList p;
    p = L->next;
    while(p)
    {
        cout<<p->data<<" ";
        p = p->next;
    }
    cout<<endl;
}

Status List_Delete(LinkList &L,int pos)
{
    int cnt = 1;
    LinkList p,q;
    p = L->next;
    while(p&&(cnt<pos-1))
    {
        cnt++;
        p = p->next;
    }
    q = p->next;
    p->next = q->next;
    free(q);
}

Status List_Update(LinkList &L,int pos,ElemType e)
{
    int cnt = 1;
    LinkList p,q;
    p = L->next;
    while(p&&(cnt<pos))
    {
        cnt++;
        p = p->next;
    }
    p->data = e;
    return OK;
}

int main()
{
    LinkList L;
    Init_LinkList(L);
    ElemType e,n,pos;
    cout<<"輸入數據的各數n:";
    cin>>n;
    for(int i=1; i<=n; i++)
    {
        cin>>e;
        Insert_List(L,i,e);
    }
    cout<<"輸入的數據如下:"<<endl;
    List_Traverse(L);
    cout<<"Input Elem e before x:"<<endl;
    cin>>e>>n;
    Insert_List(L,n,e);
    List_Traverse(L);
    cout<<"Input the del pos:";
    cin>>pos;
    List_Delete(L,pos);
    List_Traverse(L);
    cout<<"Input the change pos and Elem e:";
    cin>>pos>>e;
    List_Update(L,pos,e);
    List_Traverse(L);
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章