链表的基础操作
程序功能
输入几 就把几调到数最前面
程序步骤:
1.插入函数
2.初始化函数
3.删除节点
4.把排列展示出来
程序注意
不同函数的指针 不同
头指针定义为全局变量
代码实现截图
#include<bits/stdc++.h>
using namespace std;
struct Node{
int data;
Node *next;
};
Node *head = new Node;
// 构造 head->1->2->3.....的链表
void insert(int x) //插入函数
{
Node *temp = new Node; //创建新节点
temp->data = x; //新节点的数据域为x
temp->next = head->next; //???不懂
//原先在头节点后 现在在新节点后 说明新节点插在了头结点后
head->next = temp;
}
void init(){ //初始化函数
head->next = NULL; //前插
for(int i= 10 ; i>=1;i--){
insert(i);
}
}
void del(int x)
{
Node *Befor = head; //存放当前节点的前驱
for(Node *T = head->next ; T!=NULL ; T=T->next){
if(T->data == x){
Node *temp = T;
Befor->next = T->next;
delete temp;
return ;
}
Befor = T;
}
}
void show(int i){
cout << "这是第" << i <<"次操作"<< endl;
for(Node *T=head->next ; T!=NULL ;T=T->next ) {
cout<<T->data<<" ";
}
cout<<endl;
}
int main(){
init();
show(0);
int N;
cin>>N;
for(int i=1;i<=N;i++)
{
int x;
cin>>x;
del(x);
insert(x);
show(i);
}
}
循环链表约瑟夫环
#include<bits/stdc++.h>
using namespace std;
//定义循环链表
struct Node{
int data;
Node *pNext;
};
struct Node *p,*q,*first,*r;
int ysfh(int n,int k,int m){
//创建循环链表
first = (Node*)new Node;
first->data = 1;
first->pNext = NULL;
p=first;
for(int i=2;i<=n;i++)
{
q = new Node;
q->data = i;
q->pNext = NULL;
p->pNext = q;
p = p->pNext;
} //后插法
p->pNext = first; //循环上
p=first;
for(int i=1;i<=k-1;k++){
p=p->pNext;
}
while(p->pNext!=p) //只剩下一个节点时停止
{
for(int i=1;i<m;i++){
r=p;
p=p->pNext;//p是出局的
}
cout << p->data <<" ";
r->pNext = p->pNext;
p=p->pNext;
}
cout<<p->data<<endl;
}
int main()
{
int n,k,m;
cin>>n>>k>>m;//共n个人 从K开始报数 报数m的人出列
ysfh(n,k,m);
return 0;
}
STL链表的基本操作
STL链表的基本操作请点击
list<int> node;
//为链表赋值
for(int i=1;i<=n;i++)
node.push_back(i); //从List末端插入
//遍历链表
list<int> :: iterator it = node.begin(); //指向容器起始位置
while(node.size()>1){
it++;
//定义循环链表
if(it == node.end()) //指向末端
it = node.begin;
}
//删除节点
list<int>:: iterator next = ++it;
if(next == node.end()) next = node.begin();//定义循环链表
node.erase(--it); //删除这个节点 Node.size自动减1
it = next;//更新it