Von13 2022-04-02 11:10 采纳率: 33.3%
浏览 93

关于#链表#的问题,如何解决?

这是PTA上的两道题,是关于单链表的,我提交的答案虽然编译成功但结果却不对,我自己也看不出哪里有问题,所以在此请教。
一、链表创建
本题要求实现一个函数,建立一个链表,返回头指针(即头节点地址)
head是链表的头指针,链表上节点的定义如下:

struct node {char ch; struct node * next;}

链表上节点的数据成员ch按顺序赋值0 1 2 3 直到 n-1
函数接口定义:
在这里描述函数接口。

struct node *setlink(int n);

n 是节点个数,返回值是头指针。
裁判测试程序样例:

#include <stdio.h>
#include<stdlib.h>
struct node {int ch; struct node * next;};
int countnode(struct node * head);//此函数功能遍历链表,已定义
struct node *setlink(int N);//在代码区定义此函数
int main() {
int i,N;
struct node *head;
scanf("%d",&N);
head=setlink(N);
printf("%d", countnode(head));
return 0;
} 
/* 请在这里填写答案 */

在这里给出一组输入。例如:

5

在这里给出相应的输出。例如:

10

这是我写的,虽然能编译,但答案是错的。

struct node *setlink(int n)
{
 
struct node *head, *p;
 
for(int i=0; i<n; i++)
{
p->next=i;
head->next=p;
p=p->next;
 
}
head->next=NULL;
return(head);
}

二、链表遍历
本题要求实现一个函数,从链表的头指针开始遍历整个链表,输出每个节点字符数据。

head是链表的头指针,链表上节点的定义如下:

struct node {char ch; struct node * next;}

函数接口:

void countnode(struct node *head);

head是链表头指针,函数显示链表中节点的ch成员中字符。

裁判测试程序:

#include <stdio.h>
#include<stdlib.h>
struct  node
{int ch;
struct node * next;} 
struct node *setlink(int  N);
 
void  countnode( struct  node * head);//在下面代码区定义此函数
 
int main()
{
int i,N;
struct node *head; 
scanf("%d",&N); 
 head=setlink(N);
 countnode(head);
  return 0;
}
 
/* 请在这里填写答案 */

输入样例:

5

输出样例:

abcde

这个的问题同上面一样。

void countnode(struct node *head)
{
struct node *pt=NULL;
pt=head->next;
if (pt == NULL) {
        printf("链表为空\n");
    }
while(pt!=NULL)
{
printf("%s", pt->next);
pt=pt->next;
}
}
  • 写回答

1条回答 默认 最新

  • 浪客 2022-04-02 11:28
    关注
    
    struct node *setlink(int n)
    {
        struct node *head, *p,*q;
        q=head=(struct node * )malloc(sizeof(struct node));
        head->next=NULL;
        for(int i=0; i<n; i++)
        {
            p=(struct node * )malloc(sizeof(struct node));
            p->ch=i;//
            p->next=NULL;
            q->next=p;
            q=p;
            //head->next=p;//head不能动
            //p=p->next;
        }
        //head->next=NULL;//此时head指向末尾了。
        return(head);
    }
    
    
    
    
    int countnode(struct node * head)
    {
        struct node *p= head->next;
        while(p!=NULL)
        {
            printf("%d ",p->ch);
            p=p->next;
        }
    }
    
    
    评论 编辑记录

报告相同问题?

问题事件

  • 创建了问题 4月2日

悬赏问题

  • ¥15 校内二手商品转让网站
  • ¥20 高德地图聚合图层MarkerCluster聚合多个点,但是ClusterData只有其中部分数据,原因应该是有经纬度重合的地方点,现在我想让ClusterData显示所有点的信息,如何实现?
  • ¥100 求Web版SPC控制图程序包调式
  • ¥20 指导如何跑通以下两个Github代码
  • ¥15 大家知道这个后备文件怎么删吗,为啥这些文件我只看到一份,没有后备呀
  • ¥15 C++为什么这个代码没报错运行不出来啊
  • ¥15 一道ban了很多东西的pyjail题
  • ¥15 关于#r语言#的问题:如何将生成的四幅图排在一起,且对变量的赋值进行更改,让组合的图漂亮、美观@(相关搜索:森林图)
  • ¥15 C++识别堆叠物体异常
  • ¥15 微软硬件驱动认证账号申请