遍历链表时如何使用head指针?为何修改后仍能完整打印链表?
问题:链表插入节点后为何仍能打印完整链表?
我在遍历链表时会移动head指针到第i个位置,比如insertIthnode函数里,插入节点后返回的head已经不再指向原链表的第一个节点了,但调用后还是能打印出完整链表,这让我很困惑。
代码示例
#include <iostream> using namespace std; class Node { public: int data; Node *next; Node(int data) { this->data = data; next = NULL; } }; int length(Node *head) { int x = 0; Node *temp = head; while (temp != NULL) { x += 1; temp = temp->next; } return x; } void printIthnode(Node *head, int i) { int n = length(head); if (i < 0 || i > n - 1) { cout << -1 << endl; return; } int count = 1; while (count <= i) { head = head->next; count++; } if (head) { cout << head->data << endl; } else { cout << "-1" << endl; } } Node *takeinput() { int data; cin >> data; Node *head = NULL; Node *tail = NULL; while (data != -1) { Node *n = new Node(data); if (head == NULL) { head = n; tail = n; } else { tail->next = n; tail = n; } cin >> data; } return head; } void PrintLL(Node *head) { Node *temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } } Node *insertIthnode(Node *head, int i, int data) { if (i < 0) { return head; } else if (i == 0) { Node *n = new Node(data); n->next = head; head = n; return head; } int count = 1; while (count <= i - 1 && head != NULL) { head = head->next; count++; if (count == i - 1) { Node *n = new Node(data); n->next = head->next; head->next = n; return head; } return head; } } int main() { /*Node n1(1); Node *head=&n1; Node n2(2); Node n3(3); Node n4(4); Node n5(5); Node n6(6); n1.next=&n2; n2.next=&n3; n3.next=&n4; n4.next=&n5; n5.next=&n6; */ Node *head = takeinput(); insertIthnode(head, 3, 7); PrintLL(head); }
问题解析
1. 函数参数是传值副本,不影响原指针
C++里函数参数默认是传值传递,insertIthnode里的head只是原链表头指针的一个副本。你在函数里修改这个副本的指向(比如head = head->next),完全不会改变main函数里原本的head指针。所以main里调用PrintLL(head)时,用的还是最初指向链表第一个节点的指针,自然能打印完整链表。
2. 插入逻辑根本没执行
你的insertIthnode代码存在严重逻辑错误:
- 在
while循环内部,每次迭代都会直接return head,除了i=0的头部插入场景,其他位置的插入代码(创建新节点、修改指针)根本不会被执行。比如你调用insertIthnode(head,3,7)时,循环第一次执行head = head->next,count变成2,然后直接返回,插入操作完全没做。 - 就算逻辑修复,你在
main里也没接收函数返回的指针。比如如果是头部插入,函数返回了新的头指针,但main里的head还是旧指针,这时候打印就会漏掉新节点。
3. 正确的处理方式
- 遍历链表时,不要直接修改传入的
head参数,改用临时指针(比如Node *temp = head)移动,避免混淆。 - 修复
insertIthnode的循环逻辑,确保能定位到正确的插入位置并执行插入。比如把return head移到循环外面,并且调整count的判断逻辑。 - 在
main里接收函数返回的头指针,更新原变量:head = insertIthnode(head, 3, 7);
内容的提问来源于stack exchange,提问作者Nakul Deshmukh
相关产品推荐
相关产品推荐

