单链表实现与操作-C语言

单链表构建

1、代码实现:

代码中包含了链表的基本操作,构建以及增删改查:
1、链表的创建包含头插法和尾插法;
2、指定元素删除(修改可以直接调用此函数,实现过程相似);
3、链表的遍历。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
using namespace std;

typedef struct Node{
        int val;
        struct Node *next;

    }ListNode;

//使用尾插法创建一个带头结点的链表;
ListNode *create_list_tail(ListNode* l1, int num){
    l1 = (ListNode *)malloc(sizeof(ListNode));
    l1->next = NULL;
    ListNode *temp = NULL, *p = l1;
    for(int i = num; i--;i>=0)
    {
        temp = (ListNode *)malloc(sizeof(ListNode));
        temp->val = i;
        p->next = temp;
        p = temp;
    }
    p->next = NULL;
    return l1;
}

//使用头插法创建一个带头结点的链表;
ListNode *create_list_head(ListNode* l2, int num){
    l2 = (ListNode *)malloc(sizeof(ListNode));
    l2->next = NULL;
    ListNode *temp = NULL, *p = l2;
    for(int i = num; i--;i>=0){
        temp = (ListNode *)malloc(sizeof(ListNode));
        temp->val = i;
        temp->next = p->next;
        p->next = temp;
    }
    return l2;
}
//删除指定数字
ListNode *delete_list(ListNode* l3, int target){
    ListNode *temp, *pre;
    pre = l3;
    temp = pre->next;
    while(temp->next != NULL){
        if(temp->val == target){
            pre->next = temp->next;
            break;
        }
        pre = pre->next;
        temp = temp->next;
    }
    return l3;
}
int main()
{
    ListNode *list_head, *list_tail, *del_list,*head, *tail;
    list_tail = create_list_tail(list_tail,11);
    list_head = create_list_head(list_head,11);

    head = list_head->next;
    printf("头插法输出1-10:\n");
    while(head){
        printf("%d\t", head->val);
        head = head->next;
    }
    printf("\n尾插法输出1-10:\n");
    tail = list_tail->next;
    while(tail){
        printf("%d\t", tail->val);
        tail = tail->next;
    }
    del_list = delete_list(list_head, 4);
    printf("\n删除数字4后的链表:\n");
    tail = del_list->next;
    while(tail){
        printf("%d\t", tail->val);
        tail = tail->next;
    }
    return 0;
}


代码测试结果:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值