首页 > 编程语言 >Delete d node at nth position【1月17日学习笔记】

Delete d node at nth position【1月17日学习笔记】

时间:2024-01-17 12:25:35浏览次数:19  
标签:node run 17 int next nth 节点 指针

点击查看代码
//Delete d node at nth position
#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 = NULL;

	if (A == NULL) {
		A = temp;
	}//头指针为空时要建立globle区与heap区的link才能通过头指针索引
	else {
		node* run = A;
		while (run->next != NULL) {
			run = run->next;
		}
		run->next = temp;
	}//头指针不为空时用遍历指针索引
}

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

void Delete(int n) {
	node* run = A;
	if (n == 1) {
		A = run->next;//头指针指向2节点
		delete run;//删除1节点的动态内存
		return;
	}//遍历指针不能代替头指针与heap区建立link。但需用遍历指针指向2节点
	for (int i = 0; i < n - 2; i++) {
		run = run->next;
	}//结束时run指向n-1节点
	run->next = (run->next)->next;//n-1节点尾巴指向n+1节点
	delete run->next;//删除n节点的动态内存
}

int main() {
	A = NULL;
	insert(2);
	insert(4);
	insert(6);
	insert(5);
	print();
	int n;
	cin >> n;
	Delete(n);
	print();
}

标签:node,run,17,int,next,nth,节点,指针
From: https://www.cnblogs.com/whvivy/p/17969736

相关文章