c语言实现单链表算法示例分享

时间:2021-09-20 07:46:11

复制代码 代码如下:


#include <stdio.h>
#include <stdlib.h>
typedef char DataType;
typedef struct Node{
    DataType data;
    struct Node * Next;
}ListNode,* LinkList;
void Judement(LinkList head){ //判断分配内存
    if (!head){
        printf("Overflow.");
        exit(-1);
    }
}
LinkList CreatListF(void){ //头插法创建Single Linked List
    DataType ch;
    LinkList head = (ListNode*)malloc(sizeof(ListNode));
    Judement(head);
    ListNode* s;
    ch = getchar();
    while (ch != '\n'){
        s = (ListNode*)malloc(sizeof(ListNode));
        Judement(s);
        s->data = ch;
        s->Next = head->Next;
        head->Next = s;
        ch = getchar();
    }
    return head;
}
LinkList CreatListS(void){ //尾插法创建Single Linked List
    char ch;
    ListNode* s;
    LinkList head = (ListNode*)malloc(sizeof(ListNode));
    Judement(head);
    ch = getchar();
    while (ch != '\n'){
        s = (ListNode*)malloc(sizeof(ListNode));
        Judement(s);
        s->data = ch;
        head->Next = s;
        head = s;
        ch = getchar();
    }
    head->Next = NULL;
    return head;
}
int GetLength(LinkList head){  //获取长度
    int length = 0;
    LinkList p = head->Next;
    while (p){
        length += 1;
        p = p->Next;
    }
    return length;
}
ListNode* GetNodeById(LinkList head, int i){ //依序号查找元素
    if (i<1 || i>GetLength(head)){
        exit(1);
    }
    int j=1; //防止极端情况扫描逾界
    LinkList p = head->Next;
    while (p != NULL && j < i){
        j += 1;
        p = p->Next;
    }
    return p;
}
ListNode* GetNodeByValue(LinkList head, DataType e){ //依值查找元素
    LinkList p = head->Next;
    while (p != NULL&&p->data != e){
        p = p->Next;
    }
    return p;
}
int InsertList(LinkList head, DataType e, int i){ //插入e值在第i节点
    if (i<1 || i>GetLength(head) + 1){
        exit(1);
    }
    LinkList s = (ListNode*)malloc(sizeof(ListNode));
    s->data = e;
    LinkList q, p = head;
    int j = 1;
    while (j <= i){
        q = p;
        p = p->Next;
        j += 1;
    }
    s->Next = q->Next;
    q->Next = s;
    return 0;
}
int DeleteListNodeById(LinkList head, int i){ //依序号删除节点
    int j = 1;
    ListNode* p,* q;
    if (i<1 || i>GetLength(head)){
        exit(1);
    }
    p = head;
    while (j < i){
        p = p->Next;
        j += 1;
    }
    q = p->Next;
    p->Next = q->Next;
    free(q);
    return 0;
}
int DeleteListRepeatNode(ListNode* head){ //清除冗余数据
    ListNode* p, *q, *s;
    if (p == NULL){
        exit(1);
    }
    p = head->Next; //首节点无数据
    while (p->Next != NULL){
        q = p;
        while (q->Next != NULL){
            if (q->Next->data == p->data){
                s = q->Next;
                q->Next = q->Next->Next;
                free(s);
            }
            q = q->Next;
        }
        p = p->Next;
    }
    return 0;
}