题解 | #链表中的节点每k个一组翻转#
【模板】链表
http://www.nowcoder.com/practice/97dc1ac2311046618fd19960041e3c6f
Pre,Cur, Suf 遍历就行了 注意Suf == NULL的情况
* @file Untitled-9
* @author your name (you@domain.com)
* @brief
* @version 0.1
* @date 2022-03-20
*
* @copyright Copyright (c) 2022
* 采用Pre 前结点;
* Cur 当前结点;
* Suf 当前结点后一结点;
* 本次采用有头结点的尾插法;
* NOTICE: 对于Cur, Suf 要注意是否为NULL,
* if为NULL,就返回了, 刚开始我没有考虑Suf == NULL的情况,导致
* 5
insert 0 1
insert : 无法将“insert”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确
,然后再试一次。
所在位置 行:1 字符: 1
+ insert 0 3
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (insert:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
insert : 无法将“insert”项识别为 cmdlet、函数、脚本文件或可运行程序的名称。请检查名称的拼写,如果包括路径,请确保路径正确
,然后再试一次。
所在位置 行:1 字符: 1
+ insert 1 2
+ ~~~~~~
+ CategoryInfo : ObjectNotFound: (insert:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
,
*/
#include <bits/stdc++.h>
using namespace std;
typedef struct list{
int val;
struct list *next;
}List, *LinkList;
LinkList Insert(LinkList p, int inv, int x) {// 在inv前插入x;
LinkList Pre, Cur, Suf, Init;
Pre = p; Init = p;
Cur = Pre->next;
LinkList q = new List;
q->val = x;
if(Cur == NULL) {
q->next = Init->next;
Init->next = q;
Init = q;
return p;
}
Suf = Cur->next;// 注意,不要在前面,因为,如果Cur == NULL,Suf 就会返回,要先判断Cur是否为NULL;
while(Cur) {
if(Cur->val == inv) {
q->next = Cur;
Pre->next = q;
return Init;
} else if(Suf == NULL) {
q->next = Cur->next;
Cur->next = q;
Cur = q;
return Init;
} else {
Pre = Cur;
Cur = Suf;
Suf = Suf->next;
}
}
return Init;
}
LinkList Delete(LinkList p, int inv) { // 删除inv;
LinkList Pre, Cur, Suf, Init;
Pre = p; Init = p;
Cur = Pre->next;
if(Cur == NULL) return p;
Suf = Cur->next;
while(Cur) {
if(Cur->val == inv) {
Pre->next = Suf;
return Init;
} else if(Suf == NULL) {
return Init;
} else {
Pre = Cur;
Cur = Suf;
Suf = Suf->next;
}
}
return Init;
}
int main()
{
int n;
cin>>n;
LinkList head = new List;
head->next = NULL;
while(n--) {
string c;
cin>>c;
if(c == "insert") {
int inval, whatval;
cin>>inval>>whatval;
head = Insert(head, inval, whatval);
} else {
int inval;
cin>>inval;
head = Delete(head,inval);
}
}
head = head->next;
if(head == NULL) {
cout<<"NULL";
return 0;
}
while(head) {
cout<<head->val<<" ";
head = head->next;
}
}