如何在遍历链表时使用head



我们在head的帮助下迭代链表,也就是说,随着我们向第i个位置前进,我们正在更新head。请看一下insertIthnode的功能。我在I的位置插入我的Node,返回head,它仍然能够打印链表。我不知道怎么做?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);
}

在main((函数中,当您在";takeInput((";作用

之后,您将调用函数";insertIthnode(头,3,7(";它正在返回头(因为返回类型是Node(,但您没有在任何变量中接收到它;插入第四节点";丢失。

您的原始头部与";takeInput((";作用

如果尝试在索引0处插入第i个节点,则不会根据插入的节点进行打印。

问题是您将Node视为链表。虽然这是有效的,但链表的全部意义在于你不会失去对头部的跟踪。你可以使用两种方法:

  1. 不要从头开始迭代。相反,请使用对头部的临时引用
  2. 实现一个链表包装器。在节点上执行操作时,可以保持对头部的恒定引用

通过值传递head。对函数内接收head值的变量所做的任何更改都将仅对函数内的局部变量进行,并且在调用站点中不可见。

以您的PrintLL函数为例:

void PrintLL(Node *head) { // head is here a local variable 
Node *temp = head;
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}

这可以在没有额外变量temp的情况下重写。名称head与您用来调用函数的head不同:

void PrintLL(Node* head) {
while (head != nullptr) {
cout << head->data << ' ';
head = head->next;
}
}

并且它不会影响您作为参数传入的CCD_ 13。

类似:

void foo(int x) {
++x;
//
}
int main() {
int x = 10;
foo(x);
std::cout << x << 'n'; // prints 10
}

最新更新