C----单向链表

1、定义链表结构

#define   ElementType int
#define   ElementTypeNULL -1

//节点
typedef struct Node {
    ElementType Element;
    struct Node *Next;
} Node;


typedef Node *List;

2、链表操作


//创建一个新节点
List NewNode(ElementType elem) {
    List L = (List) malloc(sizeof(Node));
    L->Next = NULL;
    L->Element = elem;
    return L;
}

//初始化链表
List InitLink(ElementType elem) {
    return NewNode(elem);
}

//是否是最后一个节点
int IsLast(List L) {
    return L->Next == NULL;
}

//寻找尾结点
List FindEndNode(List L) {
    while (L->Next) {
        L = L->Next;
    }
    return L;
}

// 头插节点
List AddFirstNode(List L, ElementType elem) {
    List newNode = NewNode(elem);
    newNode->Next = L;
    L = newNode;
    return L;
}

// 尾插节点
List AddEndNode(List L, ElementType elem) {
    List newNode = NewNode(elem);
    List endNode = FindEndNode(L);
    endNode->Next = newNode;
    return L;
}

//获取长度
int GetLength(List L) {
    int i = 0;
    while (L) {
        i++;
        L = L->Next;
    }
    return i;
}

// 按索引插节点
List AddNodeFromIndex(List L, unsigned int Index, ElementType elem) {
    List tempNode = GetNodeFromIndex(L, Index);
    List newNode = NewNode(elem);
    newNode->Next = tempNode->Next;
    tempNode->Next = newNode;
    return L;
}

//获取指定索引的值
ElementType GetElemFromIndex(List L, unsigned int Index) {
    if (Index > GetLength(L)) {
        printf("Error: index is not true");
        return ElementTypeNULL;
    }
    return GetNodeFromIndex(L, Index)->Element;
}

//获取指定索引的节点
List GetNodeFromIndex(List L, unsigned int Index) {
    if (Index > GetLength(L)) {
        printf("Error: index is not true");
        return NULL;
    }
    int i = 0;
    while (i != Index) {
        L = L->Next;
        i++;
    }
    return L;
}

//获取前一个节点
List GetPreviousNode(List L, List node) {
    while (L->Next != node) {
        L = L->Next;
    }
    return L;
}


//取下节点
List TakeNode(List L);

// 头删节点
List DelFirstNode(List L) {
    List tempNode = L->Next;
    //释放内存
    free(L);
    return tempNode;
}


// 尾删节点
List DelEndNode(List L) {
    List endNode = FindEndNode(L);
    List preNode = GetPreviousNode(L, endNode);
    preNode->Next = NULL;
    free(endNode);
    return L;
}

// 按索引删节点
List DelNodeFromIndex(List L, unsigned int Index) {
    List tempNode = GetNodeFromIndex(L, Index);
    List preNode = GetPreviousNode(L, tempNode);
    preNode->Next = tempNode->Next;
    free(tempNode);
    return L;
}

//翻转链表
List ReverseList(List L) {
    List next;
    List prev = NULL;
    while (L != NULL){
        next = L->Next;
        L->Next = prev;
        prev = L;
        L = next;
    }
    return  prev;
}

//打印链表
void Display(List L) {
    while (L) {
        printf("%d ==>", L->Element);
        L = L->Next;
    }
    printf("NULL\n");
}
上一篇:基础数据结构:顺序表


下一篇:1顺序栈