XMUOJ上机题之链表全部操作
废话不多说,链表全操作全部奉上。
#include <stack>
void insert(node *(&head), node *(&now), int x){ // 把 x 插入到 head 的末尾。head: 目标链表头指针 now: 目标链表尾指针 x: 插入值
if(head == NULL){
head = new node;
head->val = x;
head->next = NULL;
now = head;
}
else{
node *tmp = new node;
tmp->val = x;
tmp->next = NULL;
now->next = tmp;
now = tmp;
}
return ;
}
node* createList() // 创建一个链表,返回其头指针
{ node *head = NULL;
node *now;
int x;
while(scanf("%d", &x) && x != -1){
insert(head, now, x);
}
return head;
}
node* reverseList(node* head) // 返回一个新链表,存储反转后的链表。中间用栈缓存,可以节省内存空间
{
node *head1 = NULL;
node *now;
node *p = head;
stack <int> stac;
while(p != NULL){
stac.push(p->val);
p = p->next;
}
while(!stac.empty()){
int x = stac.top(); stac.pop();
insert(head, now, x);
}
return head1;
}
node* deleteElements(node* head, int v) // 删除所有值为 v 的节点
{
node *p = head;
node *pre = head;
while(p != NULL){
if(p->val == v){
if(p == head){
head = head->next;
delete p;
p = head;
continue;
}
else{
pre->next = p->next;
delete p;
p = pre->next;
continue;
}
}
pre = p;
p = p->next;
}
return head;
}
node* merge(node* head1, node* head2) // 合并两个有序链表(从小到大),成为新链表
{//将这个函数补充完整
node *head = NULL;
node *p = head1;
node *q = head2;
node *now = NULL;
while(p != NULL && q != NULL){
int flag = 1;
int x = 0;
if(p->val <= q->val){
x = p->val;
flag = 1;
}
else{
x = q->val;
flag = 2;
}
insert(head, now, x);
flag == 1 ? p = p->next : q = q->next;
}
while(p != NULL){
insert(head, now, p->val);
p = p->next;
}
while(q != NULL){
insert(head, now, q->val);
q = q->next;
}
return head;
}