【C语言复习】单链表的初始化、插入、删除操作

记录知识点,用于复试准备中C程序的链表基础操作

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

struct LinkNode
{
    int val;
    LinkNode *next;
};

LinkNode* nodeInitial(LinkNode *head)
{
    head -> next = NULL;
    head -> val = -1;// 带头结点
    cout << "初始化完成" << endl;
    return head;
}

//尾插法
LinkNode* nodeInsert(LinkNode *head, int x)
{
    printf("开始插入数据:%d\n",x);
    LinkNode *ans = head;
    LinkNode *cur = (LinkNode*) malloc(sizeof(LinkNode));//定义节点类型时一定要为其开辟空间
    cur->val = x;
    cur->next = NULL;
    while(ans->next){
        ans = ans->next;
    }
    ans->next = cur;
    return head;
}

//在具体某个位置插入数据
LinkNode* nodeInsertPos(LinkNode *head, int x, int pos)
{
    printf("要插入的位置是:%d\n",pos);
    LinkNode* cur = head, *pre;
    LinkNode *t = (LinkNode*) malloc(sizeof(LinkNode));
    t->val = x; // 要插入的节点数据
    while(cur && pos--){
        pre = cur;
        cur = cur->next;
    }
    if(!cur && !pos){ //插入到链表的最后位置
        pre->next = t;
        t->next = NULL;
        return head;
    }
    if(!cur && pos){ //若直到链表尾部,pos还没减到0,则说明要插入的位置pos大于链表的长度
        printf("输入的位置不合法,请重新输入!\n");
        return head;
    }
    //将节点插入到pos位置
    pre->next = t;
    t->next = cur;
    return head;
}

LinkNode* nodeDelete(LinkNode *head, int pos)
{
    LinkNode *cur = head, *pre;//将要删除节点记为cur, 将要删除的前一个节点记为pre
    while(cur && pos--){
        pre = cur;
        cur = cur->next;
    }
    if(!cur){ //遍历完链表仍未找到要删除的节点位置
        printf("输入的下标有误!\n");
        return head;
    }
    pre->next = cur->next;
    free(cur);
    return head;
}

void nodePrint(LinkNode *head)
{
    cout << "打印单链表中的数据:" << endl; //这里cout和printf混着用了,可以自行将其改成printf,或增加cout的头文件
    while(head->next){
    	printf("%d====", head->next->val);
        head = head->next;
    }
    cout << endl;
}

int main()
{
	//测试
    LinkNode *head = (LinkNode*) malloc(sizeof(LinkNode));
    head = nodeInitial(head);
    nodePrint(head);
    head = nodeInsert(head, 1);
    head = nodeInsert(head, 2);
    head = nodeInsert(head, 3);
    nodePrint(head);
    head = nodeInsertPos(head, 5, 4);
    nodePrint(head);
    head = nodeDelete(head, 2);
    nodePrint(head);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值