关于链表的参数传递问题
c++吧
全部回复
仅看楼主
level 3
大佬们,不是说链表当作函数参数时,想要改变原链表的值需要使用引用传递吗,
为什么我这个delete_last_node函数能删掉原链表的最后一个节点呀。。。
但是上边的insertHead必须使用引用传递才能给原链表添加新的头节点。。
2023年09月03日 01点09分 1
level 3
typedef struct ListNode{
int val;
struct ListNode *next;
ListNode(int x) : val(x), next(NULL){};
};
2023年09月03日 01点09分 2
level 3
void insertHead(ListNode *&head, int x){
ListNode *newNode = new ListNode(x);
newNode->next = head;
head = newNode;
}
2023年09月03日 01点09分 3
level 3
void delete_last_node(ListNode *head){
ListNode *p1 = head;
ListNode *p2 = head->next;
while (p2->next != NULL) {
p1 = p2;
p2 = p2->next;
}
p1->next = NULL;
delete p2;
}
2023年09月03日 01点09分 4
level 3
void clear(ListNode *head){
if (head == NULL)
return;
ListNode *cur = head->next;
while (cur != NULL) {
head->next = cur->next;
delete cur;
cur = head->next;
}
delete head;
}
2023年09月03日 01点09分 5
level 3
void print_listnode(ListNode *head){
ListNode *cur = head;
while (cur != NULL) {
std::cout << cur->val << "->";
cur = cur->next;
}
std::cout << std::endl;
}
2023年09月03日 01点09分 6
level 3
int main(){
ListNode *node = new ListNode(0);
node->next = new ListNode(1);
node->next->next = new ListNode(2);
insertHead(node, 3);
delete_last_node(node);
print_listnode(node);
clear(node);
system("pause");
return 0;
}
2023年09月03日 01点09分 7
level 3
等等,我好像明白了
2023年09月03日 02点09分 8
level 4
指针一样是操作的本体。
2023年09月03日 04点09分 9
level 1
*&是什么语法,你写的c还是c++啊[疑问]
2023年09月03日 05点09分 10
我写的c++,也不是很懂,这里ListNode* &head应该表示指向ListNode指针的引用
2023年09月03日 05点09分
应该也可以先写成 typedef ListNode* List; 然后函数参数写 void function(List &head); (大概)
2023年09月03日 05点09分
@来一杯薄荷茶 指针了就不用引用了
2023年09月03日 09点09分
level 8
抄老师的代码
2023年09月03日 05点09分 11
level 8
没老师就抄百度,百度上我也看过,写的比你好一点
2023年09月03日 05点09分 12
1