栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【PTA】【C语言】【函数题】删除单链表的第i个结点

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【PTA】【C语言】【函数题】删除单链表的第i个结点

本题要求实现一个函数,删除单链表的第i个结点。

函数接口定义:
Node *deletelink(Node *head, int i)

在这里,head是单链表的头指针,i是待删除的结点编号。函数不需要处理单链表为空的情况。如果删除位置错误,输出"error"。

裁判测试程序样例:
#include 
#include 
#include 

typedef struct ListNode {
    int num;
    struct ListNode *next;
}Node;

Node *createlist(); 
Node *deletelink(Node *head, int i);
void display(Node *head);

int main(void)
{
    Node  *head;
     int i;
    head = createlist();
     scanf("%d",&i);
    head = deletelink(head, i);
    display(head);
    return 0;
}


输入样例1:
5
10 5 4 8 7
2

输出样例1:
10 4 8 7

输入样例2:
5
10 5 4 8 7
6

输出样例2:
error
10 5 4 8 7

所需函数代码如下: 

Node *deletelink(Node *head, int i)
{
    Node *p, *s;
    int count = 1;
    p = head;
    if (i == 1)
    {
        head = p -> next;
        return head;
    }
    while (p -> next != NULL && count < i)
	{
		s = p;
		p = p -> next;
        count++;
    }
    if (count < i)
    {
        printf("errorn");
        return head;
    }
    else
    {

        s -> next = p -> next;
        free(p);
    }
    return head;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/876730.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号