Inserting a node at beginning,全局变量头指针【1月16日学习笔记】

//inserting a node at beginning,全局变量头指针
#include<iostream>
using namespace std;

struct node {
	int data;
	node* next;
};
node* A;

void insert(int x) {
	node* temp = new node;//创建新节点
	temp->data = x;
	temp->next = A;//新节点尾巴指向1节点(无则NULL)
	A = temp;//头指针指向新节点
}

void print() {
	node* run = A;
	while (run!= NULL) {
		cout << run->data << " ";
		run = run->next;
	} cout << endl;
}

int main() {
	int x;
	while (cin >> x) {
		insert(x);
		print();
	}

}

好的,我明白了。这是一个链表操作的问题。这里给出实现函数的伪代码: ``` struct node *insert(struct node *head, char x, int i) { struct node *prev = NULL, *curr = head; struct node *new_node = (struct node *) malloc(sizeof(struct node)); new_node->data = x; new_node->next = NULL; // Handle edge case when inserting at position 1 if (i == 1) { new_node->next = head; head = new_node; return head; } // Traverse the list to find previous node int pos = 1; while (curr != NULL && pos != i) { prev = curr; curr = curr->next; pos++; } // Insert node at position i if (pos == i && curr != NULL) { prev->next = new_node; new_node->next = curr; } else { printf("Invalid position %d\n", i); } return head; } ``` 首先,我们需要定义链表的节点结构体,包含一个数据域和一个指向下一个节点的指针。在这个问题中,我们还需要一个头指针来指向整个链表的第一个节点。 在insert函数中,我们首先创建一个新的节点,设置数据域的值为x,然后将next指针设置为NULL,因为我们不知道它将被插入到哪里。 然后,我们处理一个特殊情况,如果要在第一个位置插入节点,直接把新节点插入到head之前即可。 接下来,我们使用prev指针和curr指针来找到要插入的位置。我们遍历链表,直到curr指针指向NULL(到达链表末尾)或者pos等于i。当pos等于i时,我们找到了要插入节点的位置。现在我们可以将新节点插入prev和curr之间。 最后,我们返回头指针。如果i是无效的位置,我们在函数中打印错误消息。 希望这个代码伪代码可以帮到您!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值