數據結構之線性表:單鏈表的實現

#include <iostream>
#include<algorithm>
#include<cstdio>
using namespace std;

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

//頭插法
LNode* List_HeaderInsert(LNode *&L){
    LNode *s;
    int x = 0;
    L = (LNode*)malloc(sizeof(LNode));
    L->next = NULL;
    while(x!=-1){ //輸入-1結束
        scanf("%d", &x);
        s = (LNode*)malloc(sizeof(LNode));
        s->data = x;
        s->next = L->next;
        L->next = s;
    }
    return L;
}

//尾插法
LNode *List_TailerInsert(LNode *&L){
    L = (LNode*)malloc(sizeof(LNode));
    int x = 0;
    LNode *s, *r = L;
    L->next = NULL;
    while(x!=-1){
        scanf("%d", &x);
        s = (LNode*)malloc(sizeof(LNode));
        s->data = x;
        r->next = s;
        r = s;
    }
    r->next = NULL;
    return L;
}

//按序號查找結點值
LNode *GetElem(LNode *L, int i){
    if(i==0) return L; //查找位置爲0,返回頭結點
    else if(i<0) return NULL;//查找位置不合法返回NULL
    int j = 1;
    LNode *p = L->next;
    while(p!=NULL && j<i){ //查找位置大於表長,返回NULL
        j++;
        p = p->next;
    }
    return p;
}

//按值查找結點
LNode *LocateElem(LNode *L, ElemType e){
    LNode *p = L->next;
    while(p && p->data!=e){
        p = p->next;
    }
    return p;
}

//插入結點
bool InsertNode(LNode *&L, int i, ElemType e){
    if(i<=0) return false; //插入位置不合法報錯
    LNode *s = (LNode*)malloc(sizeof(LNode));
    s->data = e;
    LNode *p = GetElem(L, i-1);
    if(p){
        s->next = p->next;
        p->next = s;
    }
    else{ //如果插入位置大於表長,則插入到表最後
        LNode *q = L->next;
        while(q->next!=NULL){
            q = q->next;
        }
        q->next = s;
        s->next = NULL;
    }
    return true;

}

bool DeleteNode(LNode *&L, int i, ElemType &e){
    if(i<=0) return false; //刪除位置不合法報錯
    LNode *p = GetElem(L, i-1);
    if(p==NULL) return false; //i大於表長報錯
    if(p->next==NULL) return false; //i大於表長報錯
    LNode *q = p->next;
    e = q->data;
    p->next = q->next;
    free(q);
    return true;
}

//求表長
int ListLength(LNode *L){
    int len = 0;
    LNode *p = L->next;
    while(p){
        len++;
        p = p->next;
    }
    return len;
}

void Print_LinkList(LNode *L){
    LNode *p = L->next;
    while(p!=NULL){
        printf("%d ", p->data);
        p = p->next;
    }
    printf("\n");
}

int main(){
    LNode *L;
    List_TailerInsert(L);
    Print_LinkList(L);
    printf("%d\n", ListLength(L));
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章