Amb*_*S J 1 c pointers linked-list
我正在完成一个Hackerrank挑战,包括将元素添加到链表并打印它.
输入具有以下格式:一组整数,其中第一个元素给出大小,其余元素是列表的组成部分.
我用Java完成了挑战,但我无法在C中完成.输入4 2 3 4 1应打印2 3 4 1,但我编码的这个片段给了我1 1 1 1 1 1 ... .{truncated}
我的方法:声明一个Node类型的新结构temp(数据输入为数据字段,下一个字段为NULL),然后以head为起点遍历链表,当它到达最后一个元素时,更改最后一个元素的下一个字段到当前元素的地址.
码:
#include <stdlib.h>
#include <stdio.h>
typedef struct Node{
int data;
struct Node* next;
}Node;
Node* insert(Node *head,int data)
{
Node temp = {data, NULL} ;
if (head == NULL)
{ head =&temp;
return head;
}
else{
Node* current = head ;
while(current->next !=NULL)
current = current->next ;
current->next = &temp;
return head;
}
}
void display(Node *head)
{
Node *start=head;
while(start)
{
printf("%d ",start->data);
start=start->next;
}
}
int main()
{
int T,data;
scanf("%d",&T);
Node *head=NULL;
while(T-->0){
scanf("%d",&data);
head=insert(head,data);
}
display(head);
}
Run Code Online (Sandbox Code Playgroud)
列表节点必须动态分配.这个
Node temp = {data, NULL} ;
Run Code Online (Sandbox Code Playgroud)
声明一个局部变量.在其声明函数范围之外引用其地址是未定义的行为.
用...来代替
Node *temp = malloc(sizeof(Node));
temp->data = data;
temp->next = NULL;
Run Code Online (Sandbox Code Playgroud)
现在thtat temp是一个指针,表达式&temp也必须被替换temp.
| 归档时间: |
|
| 查看次数: |
76 次 |
| 最近记录: |