剑指offer的题,自测都能通过,提交时牛客提示段错误
剑指off中的这2个题目: 1.反转链表 https://www.nowcoder.com/practice/75e878df47f24fdc9dc3e400ec6058ca?tpId=13&tqId=11168&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking 2.链表中的倒数第k个节点 https://www.nowcoder.com/practice/529d3ae5a407492994ad2a246518148a?tpId=13&tqId=11167&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
我反转链表的代码如下:
ListNode* ReverseList(ListNode* pHead) { stack s; while (pHead) { s.push(pHead); pHead = pHead->next; } ListNode* newHead = s.top(); s.pop(); ListNode* p = newHead; while (!s.empty()) { p->next = s.top(); s.pop(); p = p->next; } p->next = NULL; return newHead; }
倒数第k的节点的解法如下:
ListNode* FindKthToTail(ListNode* pListHead, unsigned int k) { if (pListHead == NULL) return NULL; stack s; while (pListHead != NULL) { s.push(pListHead); pListHead = pListHead->next; } for (size_t i = 0;i < k - 1;++i) { s.pop(); } return s.top(); }
我在VS中的测试代码如下:
int main() { ListNode *p1 = new ListNode(1); ListNode *p2 = new ListNode(2); ListNode *p3 = new ListNode(3); ListNode *p4 = new ListNode(4); p1->next = p2; p2->next = p3; p3->next = p4; p4->next = NULL; // //ListNode *ret = FindKthToTail(p1, 2); //输出3 //cout << ret->val << endl; ListNode *ret = ReverseList(p1); while (ret) { cout << ret->val << " "; ret = ret->next; } cout << endl;//输出 4 3 2 1 return 0; }为什么在牛客中提交就提示:
您的代码已保存
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
case通过率为0.00%
段错误:您的程序发生段错误,可能是数组越界,堆栈溢出(比如,递归调用层数太多)等情况引起
case通过率为0.00%