【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(); /*根据用户输入的整数n,创建具有n个结点的单链表。裁判实现,细节不表*/
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("error\n");
        return head;
    }
    else
    {

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

你可能感兴趣的:(c语言,PTA)