这很明显是一个链表的题目,考链表的基础知识
开始先定义了一个结构体节点,里面有一个val和一个指向node结构体的指针next
然后通过typedf将linkedlist表示为一个指向node的指针
insert代表右插入
push是左插入
#include <iostream>
using namespace std;
typedef struct Node
{int val;Node *next;
} Node,*linkedList;
//后插
linkedList insert(Node *list, int x)
{Node *p = new Node;p->val = x;p->next = list->next;list->next = p;return p;
}
//前插 -->(先后插再换值,相当于后插,多了一步换值)
linkedList push(Node *list, int x)
{Node *p = new Node;p->val = list->val;list->val = x;p->next = list->next;list->next = p;return list;
}
//删除
void remove(Node *list)
{Node *p = list->next;list->val = p->val;list->next = p->next;delete p;
}int main()
{int n, m, ma[100005] = {0}, k, p, x;linkedList list = new Node;list->next = NULL;linkedList *list1;list1 = new linkedList[100005];list1[1] = insert(list, 1);cin >> n;for (int i = 2; i <= n; i++){cin >> k >> p;if (p == 1) //前插{list1[i] = insert(list1[k], i);}else //后插{list1[i] = push(list1[k], i);list1[k] = list1[i]->next;}}
//删除cin >> m;for (int i = 1; i <= m; i++){cin >> x;if (ma[x] == 1) //避免重复删除continue;ma[x] = 1;remove(list1[x]);}//打印结果Node *L = list->next;while (L){cout << L->val << " ";L = L->next;}return 0;
}