现在的位置: 首页 > 综合 > 正文

数据结构上机测试2-1:单链表操作A

2018年04月15日 ⁄ 综合 ⁄ 共 1789字 ⁄ 字号 评论关闭

最近在复习之前的链表,想把之前写过的代码复习一下。。

华丽丽的从中间发现了一个巨大巨大巨大!!!的问题------“格式”。

下面这个题我PE了五遍。。其实题目还是挺简单的,但是没有注意链表输出时最后一个数字应该是换行不是空格,多写了一个空格,所以就在不停的PR,PR,PR。。。

注意格式!!!

总结一下:

1.应该是在句末循环输出的时候多加了一个空格,应该单独拿出来写最后一个。

2.在结束的时候多加了换行。

经验:本题在输出的时候在句末多加了空格。。。

数据结构上机测试2-1:单链表操作A



Time Limit: 1000ms   Memory limit: 4096K  有疑问?点这里^_^

题目描述

输入n个整数,先按照数据输入的顺序建立一个带头结点的单链表,再输入一个数据m,将单链表中的值为m的结点全部删除。分别输出建立的初始单链表和完成删除后的单链表。

输入

第一行输入数据个数n;

第二行依次输入n个整数;

第三行输入欲删除数据m。

输出

第一行输出原始单链表的长度;

第二行依次输出原始单链表的数据;

第三行输出完成删除后的单链表长度;

第四行依次输出完成删除后的单链表数据。

示例输入

10
56 25 12 33 66 54 7 12 33 12
12

示例输出

10
56 25 12 33 66 54 7 12 33 12
7
56 25 33 66 54 7 33

正确的代码。。

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int date;
    struct node *next;
};

struct node *head,*p,*tail;

int main()
{
    int i;
    int n;
    scanf("%d",&n);

    head = new node;
    head->next = NULL;
    tail = head;
    for(i=0; i<n; i++)
    {
        p = new node;
        scanf("%d",&p->date);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    int m;//要删除的数字
    int t=0;//要删除的数字的个数
    scanf("%d",&m);
    printf("%d\n",n);
    p = head->next;
    while(p->next)
    {
        printf("%d ",p->date);
        p = p->next;
    }
    printf("%d\n",p->date);
    p = head;
    while(p->next)
    {
        if(p->next->date==m)
        {
            t++;
            tail = p->next;
            p->next = tail->next;
            free(tail);
        }
        else
            p = p->next;
    }
    printf("%d\n",n-t);
    p = head->next;
    while(p->next)
    {
        printf("%d ",p->date);
        p = p->next;
    }
    printf("%d\n",p->date);

    return 0;
}

一直在PR的代码。。

#include <stdio.h>
#include <stdlib.h>

struct node
{
    int date;
    struct node *next;
};

struct node *head,*p,*tail;

int main()
{
    int i;
    int n;
    scanf("%d",&n);

    head = new node;
    head->next = NULL;
    tail = head;
    for(i=0; i<n; i++)
    {
        p = new node;
        scanf("%d",&p->date);
        p->next = NULL;
        tail->next = p;
        tail = p;
    }
    int m;//要删除的数字
    int t=0;//要删除的数字的个数
    scanf("%d",&m);
    printf("%d\n",n);
    p = head->next;
    while(p)
    {
        printf("%d ",p->date);
        p = p->next;
    }

    p = head;
    while(p->next)
    {
        if(p->next->date==m)
        {
            t++;
            tail = p->next;
            p->next = tail->next;
            free(tail);
        }
        else
            p = p->next;
    }
    printf("\n%d\n",n-t);
    p = head->next;
    while(p->next)
    {
        printf("%d ",p->date);
        p = p->next;
    }
    printf("%d\n",p->date);

    return 0;
}
 

其实我有注意到第二个,但是忘记了第一个,好伤心==、

抱歉!评论已关闭.