链表创建和链表遍历

这是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,*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;
    }
    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;
}
}

  • 2
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值