关于单链表问题
本帖最后由 chinggggg 于 2018-9-30 17:35 编辑目的:创建单链表,输入,然后打印出来;
编译运行结果:可以输入,但ENTER之后没反应;;
奉上代码:
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef struct Node
{
int data;
struct Node *next;
}DLinklist;
//创建链表并写入
void InitList(DLinklist *head , int n)
{
int i;
DLinklist *p,*s;
head = (DLinklist*)malloc(sizeof(DLinklist));
head -> next = NULL;
p = head;
for(i = 1;i <= n;++i)
{
s = (DLinklist*)malloc(sizeof(DLinklist));
scanf("%d",&s -> data);
s -> next = NULL;
p -> next = s;
p = s;
}
}
//打印链表
void print(DLinklist *head)
{
DLinklist *s = head -> next;
while(s -> next != NULL)
{
printf("%d",s -> data);
s = s -> next;
}
}
int main()
{
DLinklist *head;
InitList(head,8);
print(head);
return 0;
} #include <stdio.h>
#include <stdlib.h> //有这个就不用 malloc.h 了
typedef struct Node
{
int data;
struct Node *next;
}DLinklist;
//创建链表并写入
void InitList(DLinklist **head , int n)
{
int i;
DLinklist *p, *s;
*head = (DLinklist*)malloc(sizeof(DLinklist));
printf("请输入%d个元素\n", n);
scanf("%d", &(*head)->data);
(*head)->next = NULL;
p = (*head);
for(i = 2; i <= n; ++i)
{
s = (DLinklist*)malloc(sizeof(DLinklist));
scanf("%d", &s->data);
s->next = NULL;
p->next = s;
p = s;
}
}
//打印链表
void print(DLinklist *head)
{
DLinklist *s = head;
while(s)
{
printf("%d ",s->data);
s = s->next;
}
}
int main()
{
DLinklist *head;
InitList(&head,8);
print(head);
return 0;
}不用发两个地方
页:
[1]