【数据结构】链表实现


#include <stdio.h>
#include <stdlib.h>
struct Node;
typedef struct Node *PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;

struct Node
{
    int X;
    Position next;
};

//======================function=========================
//=======================================================
//=======================================================

Position Last(List L) //return the position of the last node
{
    Position P, previousOne;
    P = L;
    while (P->next!=NULL) {
        previousOne=P;
        P=P->next;
    }
    return P;
}

Position Find(List L, int x)
{
    Position P; P=L;
    while (P!=NULL&&P->X!=x) {
        P=P->next;
    }
    return P;
}

Position FindPrevious(List L, int x)
{
    Position P; P=L;
    while (P->next!=NULL&&P->next->X!=x) {
        P=P->next;
    }
    return P;
}

void append(int x,List L)
{
    Position LastOne=Last(L);
    Position NewNode;
    NewNode=malloc(sizeof(struct Node));
    LastOne->next=NewNode;
    NewNode->X=x;
    NewNode->next=NULL;
}

void printList(List L)
{
    Position P; P=L;
    while (P!=NULL) {
        printf("%d ",P->X);
        P=P->next;
    }
}

void insert(List L, int x, Position P) //插入到P的后面
{
    Position NewNode=malloc(sizeof(struct Node));
    NewNode->next=P->next;
    P->next=NewNode;
    NewNode->X=x;
}

void insertToNum(List L,int x, int num)//插到第numf个数后面
{
    Position P; P=L;
    for (int n=1; n<num; n++) {
        P=P->next;
    }
    insert(L, x, P);
}

void delete(List L,int x) //删除列表中第一个出现的x
{
    Position P=Find(L, x), P_previous=FindPrevious(L, x);
    P_previous->next=P->next;
    free(P);
}

void empty(List L)
{
    Position P;
    Position tmP;
    P=L->next; L->next=NULL; L->X=0;
    while (P!=NULL) {
        tmP=P->next;
        free(P);
        P=tmP;
    }
}

int isEmpty(List L)
{
    return L->next==NULL;
}

int isLast(List L, Position P)
{
    return P->next==NULL;
}

void Allfunc()
{
    printf("==========All functions=========\nLast/Find/Findprevious/append/\nprintList/insert/insertToNum/\ndelete/empty/isLast/isEmpty/\n================================\n");
}

//========================main function========================

int main(int argc, const char * argv[])
{
    List L; struct Node N1; L=&N1; //创建完成含有一个节点的列表
    //====================================
    //
    //     manipulate the List here
    //
    //====================================
    return 0;
}

发布了51 篇原创文章 · 获赞 5 · 访问量 4194

猜你喜欢

转载自blog.csdn.net/qq_43519498/article/details/97274783