/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
struct ListNode* cur = head;
struct ListNode* newNode = NULL;
int j=0;
while(cur)
{
++j;
struct ListNode* next = cur->next;
cur->next = newNode;
newNode = cur;
cur = next;
}
*returnSize = j;
int i=0;
int *array = (int*)malloc(sizeof(int)*(j));
while(cur)
{
array[i++] = cur->val;
cur = cur->next;
}
return array;
}
输入一个链表的头节点,从尾到头反过来返回每个节点的值(用数组返回)。
。。我认为这个没有毛病,为什么结果只是地址呢
基于new bing的编写:
在这段代码中,存在一个问题是在反转链表的过程中,cur 指针已经被改变了,所以在第二个 while 循环中 cur 已经指向了 NULL。
应该在第二个 while 循环中使用 newNode 指针作为遍历链表的指针,因为它现在指向了反转后链表的头节点。修改后的代码如下:
int* reversePrint(struct ListNode* head, int* returnSize){
struct ListNode* cur = head;
struct ListNode* newNode = NULL;
int j=0;
while(cur)
{
++j;
struct ListNode* next = cur->next;
cur->next = newNode;
newNode = cur;
cur = next;
}
*returnSize = j;
int i=0;
int *array = (int*)malloc(sizeof(int)*(j));
while(newNode) // 使用 newNode 遍历链表
{
array[i++] = newNode->val;
newNode = newNode->next;
}
return array;
}
此时又出现一个问题:在计算某一位置周围8个区域雷的个数时,如果该位置在数组边界位置则会出现数组下标访问越界问题。
所以,假如要打印10*10的棋盘,为了保证两个二维数组访问时的合法性,我们必须在其边界加上一圈元素,即变成了12*12的二维数组,如下图,但多加的这一圈元素不用打印出来,我们心里知道就行。
真实打印的棋盘如下(为了便于输入坐标进行排雷,我们给该棋盘加上坐标编号):
某一无雷坐标展开如下:
在开始本次游戏编程前,我们先新建一个头文件(game.h:用来存放各种函数声明等)和两个源文件(game.c:存放各种函数具体实现;test.c:存放主函数)
既然是通过数组返回链表的结点值,函数里不需把链表逆序后再装入数组,直接把链表结点值逆序存入数组即可,修改如下,供参考:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* Note: The returned array must be malloced, assume caller calls free().
*/
int* reversePrint(struct ListNode* head, int* returnSize){
struct ListNode* cur = head;
int j=0;
while(cur)
{
++j;
cur = cur->next;
}
*returnSize = j;
int i=j-1;
int *array = (int*)malloc(sizeof(int)*(j));
cur = head;
while(cur)
{
array[i--] = cur->val;
cur = cur->next;
}
return array;
}