【数据结构】单链表的初始化及其运算操作

#include 
#include 
#include 
using namespace std;

//定义单链表的节点
typedef struct LNode{
    int data;
    struct LNode *next;
}LNode, *LinkList;

bool InsertPriorNode(LinkList &L,LNode *p, LNode *s);
bool InsertNextNode(LNode *p, int e);
LNode *  GetElem(LinkList L, int i);

//初始化链表
bool InitList(LinkList &L){
    L = (LNode *)malloc(sizeof(LNode));
    if(L == NULL){
        return false;
    }
    L->next = NULL;
    L->data = 3;
    return true;
}

//按位插入链表元素
bool ListInsert(LinkList &L, int i, int e){
    LNode *p = L;
    int j = 0;
    while(p != NULL && j < i-1){
        p = p->next;
        j++;
    }
    if(p == NULL) return false;
    return InsertNextNode(p,e);

}

//在指定节点后插入元素
bool InsertNextNode(LNode *p, int e){
    if(p == NULL){
        return false;
    }
    LNode *s = (LNode *)malloc(sizeof(LNode));
    if(!s){
        return false;
    }
    s->data = e;
    s->next = p->next;
    p->next = s;
    return true;
}

//在指点节点前插入元素
bool InsertPriorNode(LinkList &L,LNode *p, LNode *s){
    if(p == NULL || s == NULL){
        return false;
    }
    s->next = p->next;
    p->next = s;

    swap(p->data, s->data);
    return true;
}

//打印链表
void PrintList(LinkList L){
    LNode *p;
    p = L;
    p = p->next;
    while(p!=NULL){
        cout<<p->data<<" ";
        p = p->next;
    }
    cout<<endl;

}

//打印单个节点
void PrintNode(LNode *p){
    if(!p){
        cout<<"NULL"<<endl;
    }
    cout<<p->data<<endl;
}



//单链表按位查找
LNode *  GetElem(LinkList L, int i){
    if(i == 0){
        return L;
    }
    if(i < 1) return NULL;
    int j = 0;
    LNode *p = L;
    while(p && j<i){
        p = p->next;
        j++;
    }
    return p;
}

//单链表按元素查找
LNode * LocateElem(LinkList L, int e){
    LNode *p = L->next;
    while(p && p->data != e)
        p = p->next;
    return p;
}



//获得单链表的长度
int length(LinkList L){
    LNode *p = L->next;
    int len = 0;
    while(p){
        p = p->next;
        len++;
    }
    return len;
}

//尾插法建立单链表
LinkList List_TaiInsert(LinkList &L){
    int x;
    cin>>x;
    LNode *r;
    r = L;
    while(x!=-1){
        InsertNextNode(r, x);
        r = r->next;
        cin>>x;
    }
    r->next = NULL;
}

//使用头插法反转链表,在初始化链表时,一定要将next置空
LinkList reverseList(LinkList &L){
    LNode *p = L->next;
    LNode *newL = (LNode *)malloc(sizeof(LNode));
    newL->next = NULL;
    while(p){
        int e = p->data;
        LNode *s = (LNode *)malloc(sizeof(LNode));
        if(!s) return NULL;
        s->data = e;
        s->next = newL->next;
        newL->next = s;
        p = p->next;
    }
    L = newL;
    return L;
}

int main() {
    LinkList L;
    InitList(L);
    List_TaiInsert(L);
    PrintList(L);
    reverseList(L);
    PrintList(L);
    return 0;
}

你可能感兴趣的:(数据结构)