322 字
1 分钟
链表——删除任意节点
链表任意位置删除节点
本文我将继续带你用c/cpp实现链表删除节点的操作。
首先,砸门有这么个链表

实现要点
1)假设我们要删去3号节点,那么我们就得把n-1号节点连接上n+1号节点。
我们不得不去考虑特殊情况,比如说要删除第一个节点。那么就得把head连接在第二个节点上面!
2)从链表上剥离的那个节点并不会消失,他还占据一部分内存,因此要我们手动释放!
优先实现main函数
int main(){ head = NULL; Insert(2); Insert(4); Insert(6); Insert(5); Print(); int n; cout<<("Enter a position\n"); cin>>n; Delete(n); Print(); return 0;}我们在main函数里创建了个链表,并调用了Insert, Print和Delete函数,当然我们要自己去实现它!
这段程序没有做异常处理,所以我们始终认为给出的位置是有效位置!
实现Insert函数
这里实现尾插法,得插在尾部
实现代码如下(ps:依旧图省事没有做内存处理😋,大佬勿怪)
void Insert(int data){ Node* temp = new Node(); temp->data=data; temp->next=NULL; if(head==NULL){ head=temp; return; } Node* temp2; temp2 = head; while(temp2->next!=NULL){ temp2=temp2->next; } temp2->next=temp;}//插在尾部实现print函数
这个我们前面实现了很多次了,还是利用一个指针变量来遍历链表!
void Print(){ Node* temp = head; while(temp != NULL){ printf("%d",temp->data); temp = temp->next; } printf("\n");}完整cpp代码
#include<iostream>using namespace std;struct Node { int data; Node* next;};Node* head;void Insert(int data){ Node* temp = new Node(); temp->data=data; temp->next=NULL; if(head==NULL){ head=temp; return; } Node* temp2; temp2 = head; while(temp2->next!=NULL){ temp2=temp2->next; } temp2->next=temp;}//插在尾部void Print(){ Node* temp = head; while(temp != NULL){ printf("%d",temp->data); temp = temp->next; } printf("\n");}void Delete(int n){ Node* temp1=head; if(n==1){ head=temp1->next;//处理删除头部的特殊情况 delete temp1; return; } int i; for(i=0;i<n-2;i++){ temp1=temp1->next;//实现到达n-1的位置 } Node* temp2=temp1->next;//实现获得目标节点的位置! temp1->next=temp2->next;//n-1连上第n+1的节点 delete temp2;}//删除指定位置的节点int main(){ head = NULL; Insert(2); Insert(4); Insert(6); Insert(5); Print(); int n; cout<<("Enter a position\n"); cin>>n; Delete(n); Print(); return 0;}部分信息可能已经过时









