C语言-链表基础练习

练习一:

实现:将元素e构造成结点,插入链表并使之成为链表的第i个结点。(i从1开始)

要求:

  1. 链表不带头结点的链表(即链表中的第一个节点就为有数据有效节点,当链表为空链表时,list为NULL)。
  2. 如果位置i不合理,则使之成为第一个结点。
  3. 函数返回值为链表的首节点的地址。
    typedef struct node
    {
        int data;
        struct node * next;
    } Node;
    
    Node * insert(Node * list, int i, int e) {
        // TODO:
        //在这里面插入所写的代码
    }

    答案(不止一种,这里只是示例):

    #include<stdio.h>
    typedef struct node
    {
        int data;
        struct node* next;
    } Node;
    
    Node* insert(Node* list, int i, int e) {
        // TODO:
        int m = 0;
        Node* a = NULL, * p = list;
        Node* b = (Node*)malloc(sizeof(Node));
        b->data = e;
        b->next = NULL;
        while (p && m < (m - 1))
        {
            m++;
            a = p;
            p = p->next;
        }
        if (m > 1 || p)
        {
            b->next = a->next;
            a->next = b;
        }
        else
        {
            b->next = list;
            list = b;
        }
        return list;
    }

练习二:

实现:将元素e构造成结点,插入第一个值为x的链表结点之前。

要求:

  1. 链表不带头结点(同练习一)。
  2. 如果没有x,则使之成为第一个结点。
  3. 函数返回值为链表的首节点的地址。
    typedef struct Node
    {
        int data;
        struct Node * next;
    } Node;
    
    Node * insert(Node * list, int x, int e) {
        // TODO:
        //在这里面完善代码
    }

    答案(不止一种,这里只是示例):

    #include<stdio.h>
    #include<stdlib.h>
    typedef struct Node
    {
    	int data;
    	struct Node* next;
    } Node;
    Node* insert(Node* list, int x, int e) 
    {
    	// TODO:
    	Node* a = NULL, * p = list;
    	Node* b = (Node*)malloc(sizeof(Node));
    	b->data = e;
    	b->next = NULL;
    	while (p && p->data != x)
    	{
    		a = p;
    		p = p->next;
    	}
    	if (p || p != list)
    	{
    		b->next = a->next;
    		a->next = b;
    	}
    	else
    	{
    		b->next = list;
    		list = b;
    	}
    	return list;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

[小yuan絮絮叨叨]

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值