单向链表 C语言实现

链表

时间复杂度

类型数组链表
查找O(1)O(n)
插入O(n)O(1)
删除O(n)O(1)

链表的节点

struct node{
    int data;
    struct node* nxt;
};
typedef struct node Node;

顺序创建链表

Node* createLinkList(int n){
    Node* head = (Node*) malloc(sizeof(Node));
    Node* end = (Node*) malloc(sizeof(Node));
    head = end;
    int val = 0;
    for (int i = 1; i <= n; ++i) {
        Node* crt = (Node*) malloc(sizeof(Node));
        scanf("%d", &val);
        crt->data = val;
        end->nxt = crt;
        end = crt;
    }
    end->nxt = NULL;
    return head;
}

空间释放

void free_list(Node* head){
    Node* temp;
    do{
         temp = head->nxt;
         free(head);
         head = temp;
    }while (head->nxt != NULL);
}

操作

遍历

void print_list(Node* head){
    while (head->nxt != NULL){
        head = head->nxt;
        printf("%d ", head->data);
    }
    printf("\n");
}

根据索引查找

void query(Node* head, int n){
    for (int i = 0; i < n; ++i) {
        head = head->nxt;
    }
    printf("%d\n", head->data);
}

根据索引修改

void change(Node* head, int n, int val){
    for (int i = 0; i < n; ++i) {
        head = head->nxt;
    }
    head->data = val;
}

根据索引插入

void insert(Node* head, int n, int val){
    for (int i = 0; i < n; ++i) {
        head = head->nxt;
    }
    Node *temp = (Node*)malloc(sizeof(Node));
    temp->data = val;
    temp->nxt = head->nxt;
    head->nxt = temp;
}

根据索引删除

void delete_node(Node* head, int n){
    for (int i = 0; i < n - 1; ++i) {
        head = head->nxt;
    }
    Node *temp = head->nxt;
    head->nxt = temp->nxt;
    free(temp);
}

合并两个链表

//时间复杂度O(1)
void emerge(Node* head1, Node* head2){
    while (head1->nxt != NULL){
        head1 = head1->nxt;
    }
    head1->nxt = head2->nxt;
    free(head2);
}

主函数

int main() {
    Node* head1 = createLinkList(5);
    Node* head2 = createLinkList(3);
    print_list(head1);
    query(head1, 5);
    change(head1, 5, 30);
    print_list(head1);
    //在第三个位置后插入6
    insert(head1, 3, 6);
    print_list(head1);
    //删掉6
    delete_node(head1, 4);
    print_list(head1);
    emerge(head1, head2);
    print_list(head1);
    free_list(head1);
    free_list(head2);
    free(head1), free(head2);
    head1 = NULL;
    head2 = NULL;
}
/*
input:
1 2 3 4 5
9 10 11
output:
1 2 3 4 5 
5
1 2 3 4 30 
1 2 3 6 4 30 
1 2 3 4 30 
1 2 3 4 30 9 10 11 

 */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值