初学者,求解单链表的问题
一个带头结的单链表存储以整型数设计一算法 统计链表中值为3的倍数结点的个数
函数:int countx (node*head)
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node *Node;
tyoedef struct node{
int Num;
Node Next;
}node;
/* TODO (Chauncy#1#): Test1test */
int main(){
Node Head=(Node)malloc(sizeof(struct node));//头结点,本身不保存数据,你要想保存也行,不过需要改点代码
Node temp=Head;//temp指向链表尾
int num;
printf("-----------scan---------\n");
while(scanf("%d",&num)==1){//遇到第一个非数字的字符就退出循环
temp->Next=(Node)malloc(sizeof(struct node));
temp->Next->Num=num;
temp=temp->Next;
}
temp->Next=NULL;//把链表尾的指针写上NULL
printf("-----------print---------\n");
temp=Head->Next;//temp重新指向第一个要输出的位置
for(int i=1;temp;i++){//i做计数器
if(i%3==0)printf("%d ",temp->Num);
temp=temp->Next;
}
return 0;
}[此贴子已经被作者于2016-9-8 15:35编辑过]

程序代码:#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct Node
{
int data;
struct Node * pNext;
}NODE, * PNODE;
int main(void)
{
int num, j = 0;
PNODE pHead = (PNODE)malloc(sizeof(NODE));
if(NULL == pHead)
{
printf("动态内存分配失败,头结点未能创建!\n");
exit(-1);
}
//pHead->pNext = NULL;
PNODE pTail = pHead;
printf("请输入要放入链表中的元素:\n");
while(1)
{
scanf("%d", &num);
pTail->pNext = (PNODE)malloc(sizeof(NODE));
if(NULL == pTail->pNext)
{
printf("动态内存分配失败,新结点未能创建!\n");
exit(-1);
}
pTail->data = num;
if(getchar() == '\n')
break;
pTail = pTail->pNext;
}
pTail->pNext = NULL;
/*------print------*/
printf("-----------print---------\n");
printf("你所创建的链表为:\n");
pTail = pHead;
for(int i = 0; pTail; ++i)
{
printf("%d ", pTail->data);
pTail = pTail->pNext;
}
printf("\n");
/*统计链表中值为3的倍数结点的个数;可另外写成函数*/
pTail = pHead;
for(i = 0; pTail; ++i)
{
if(pTail->data % 3 == 0)
++j;
pTail = pTail->pNext;
}
printf("能被3整除的元素的结点个数为:%d\n", j);
printf("\n");
return 0;
}
同时也感谢楼上;