LeetCode 2326. Spiral Matrix IV:ListNode空指针访问错误排查
LeetCode 2326. 螺旋矩阵IV 运行时错误原因分析
问题背景
我在解决LeetCode 2326题(螺旋矩阵IV)时,采用四个边界指针的思路实现,但触发了运行时错误:
Line 46: Char 56: runtime error: member access with null pointer of type 'ListNode' (solution.cpp)
SUMMARY: UndefinedBahaviorSanitizer: undefined-behavior prog_joined.cpp:55:46
题目要求:给定两个整数m和n表示矩阵维度,以及一个整数链表的head,生成m x n矩阵,按顺时针螺旋顺序填充链表元素,剩余空位填-1并返回矩阵。
我的实现代码如下:
class Solution { public: vector<vector<int>> spiralMatrix(int m, int n, ListNode* head) { vector<vector<int>> ans(m, vector<int>(n, -1)); int top = 0; int bottom = m - 1; int left = 0; int right = n - 1; int dir = 0; while(head){ switch(dir){ case 0:{ for(int i=left;i<right;i++){ ans[top][i]=head->val; head=head->next; } top++; dir=(dir+1)%4; break; } case 1:{ for(int i=top;i<bottom;i++){ ans[i][right]=head->val; head=head->next; } right--; dir=(dir+1)%4; break; } case 2:{ for(int i=right;i>=left;--i){ ans[bottom][i]=head->val; head=head->next; } bottom--; dir=(dir+1)%4; break; } case 3:{ for(int i=bottom;i>=top;--i){ ans[i][left]=head->val; head=head->next; } left++; dir=(dir+1)%4; break; } } } return ans; } };
错误原因
1. 未在填充过程中实时检查链表状态
外层while(head)仅在进入方向切换前判断链表是否有剩余元素,但每个方向的填充循环内部没有在每次赋值前再次检查head。例如,当链表元素在某个方向的填充中途耗尽(head变为null),循环仍会继续执行下一次迭代,此时访问head->val就会触发空指针访问错误。
2. 循环边界条件错误
部分方向的填充范围不完整:
- 第0方向(从左到右)的循环条件是
i < right,会漏掉right位置的元素,导致单行矩阵无法填充完整; - 第1方向(从上到下)的循环条件是
i < bottom,会漏掉bottom位置的元素,导致单列矩阵无法填充完整。
这类边界错误会让后续逻辑在链表元素耗尽后仍可能进入循环,进一步触发空指针问题。
修复建议
针对上述问题,需要做两处修改:
- 在每个填充循环的每次迭代前检查
head是否为空,为空则立即终止循环; - 修正循环边界条件,确保每个方向的填充范围覆盖所有需要填充的位置。
修复后的核心代码片段示例:
case 0:{ for(int i = left; i <= right; ++i){ if(!head) break; ans[top][i] = head->val; head = head->next; } top++; dir = (dir + 1) % 4; break; } case 1:{ for(int i = top; i <= bottom; ++i){ if(!head) break; ans[i][right] = head->val; head = head->next; } right--; dir = (dir + 1) % 4; break; } // case2和case3同理,保持循环范围为完整区间,并添加head空指针检查
内容的提问来源于stack exchange,提问作者Yash
相关产品推荐
相关产品推荐

