链表创建和链表遍历

链表创建和链表遍历,第1张

这是PTA上的两道题,是关于单链表的,我提交的答案虽然编译成功但结果却不对,我自己也看不出哪里有问题,所以向大佬们请教。



一、链表创建

本题要求实现一个函数,建立一个链表,返回头指针(即头节点地址)

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

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

链表上节点的数据成员ch按顺序赋值0,1,2,3......至n-1

函数接口定义:
 

在这里描述函数接口。


例如:

struct node *setlink(int n);

n 是节点个数,返回值是头指针

裁判测试程序样例:

在这里给出函数被调用进行测试的例子。


例如: 

#include 

#include

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; ich=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 
#include
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;
}
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/563874.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-03
下一篇 2022-04-03

发表评论

登录后才能评论

评论列表(0条)

保存