写这道题是为了记录一下申请结构体是指针地址的问题;
题目链接
本题要求实现一个函数,按输入数据的逆序建立一个链表。
函数接口定义:
struct ListNode *createlist();
函数createlist利用scanf从输入中获取一系列正整数,当读到−1时表示输入结束。按输入数据的逆序建立一个链表,并返回链表头指针。链表节点结构定义如下:
struct ListNode {
int data;
struct ListNode *next;
};
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int data;
struct ListNode *next;
};
struct ListNode *createlist();
int main()
{
struct ListNode *p, *head = NULL;
head = createlist();
for ( p = head; p != NULL; p = p->next )
printf("%d ", p->data);
printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */
地址奇怪的输出 本片博客的记录对象
for (int i = 0; i < 5; i++) {
ListNode cur;
printf("%d\n", &cur);
}
/* 输出地址相同
605746920
605746920
605746920
605746920
605746920
*/
for (int i = 0; i < 5; i++) {
//struct ListNode* cur = (struct ListNode*)malloc(1 * sizeof(struct ListNode));
ListNode *cur = (ListNode*) malloc (sizeof(ListNode));
printf("%d\n", cur);
}
/*
* 输出地址不同
1050487984
1050486304
1050486784
1050487504
1050486464
*/
对于这个输出感到很奇怪
解题代码
struct ListNode* createlist() {
struct ListNode* p = NULL;
int data;
while (scanf("%d", &data) && data != -1) {
struct ListNode* cur = (struct ListNode*)malloc(1 * sizeof(struct ListNode));
cur->data = data;
cur->next = p;
p = cur;
}
return p;
}