题解 | #【模板】链表#
【模板】链表
https://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
本题主要进行 在指定位置插入节点 以及 删除指定位置节点 的链表操作的模拟(本题解使用带头节点的链表)
首先在结构体中定义用于存储节点数据的
data
和用于指向下一个节点的结构体指针next
。
对于插入操作,需要在第一次出现指定值的节点之前的位置进行节点的插入,因此需要两个指针,
p
指针向后遍历链表寻找指定值节点,q
指针跟随在p
指针之前,以便于新节点的插入。当p
指针找到指定值节点或为空时,便new
一个新节点,将其插入到q
节点之后即可。
对于删除操作,与插入操作类似,依然需要
p
和q
两个指针,当p
指针找到指定位置后,将q
指针的next
指向p
指针的next
,然后将p
指针的next
置空,即可delete p
,达到删除指定位置节点的要求。
#include<iostream> using namespace std; struct List { int data; List* next; }; void insert(List* p, int x, int y) // 在指定位置插入节点 { List* q = p; p = p->next; while(p != NULL) { if(p->data == x) { break; } q = p; p = p->next; } List* t = new List(); t->data = y; q->next = t; t->next = p; } void del(List* p, int x) // 删除指定位置节点 { List* q = p; p = p->next; while(p != NULL) { if(p->data == x) { q->next = p->next; p->next = NULL; delete p; return ; } q = p; p = p->next; } } int main() { int n; cin>>n; List* head = new List(); head->next = NULL; // 创建带头节点的链表 for(int i = 0; i < n; i++) { string op; cin>>op; if(op == "insert") { int x, y; cin>>x>>y; insert(head, x, y); } if(op == "delete") { int x; cin>>x; del(head, x); } } List* f = head->next; // 因为带头节点,因此需要从head->next开始遍历链表 if(f == NULL) { cout<<"NULL"; } while(f != NULL) { cout<<f->data<<" "; f = f->next; } return 0; }