1 插入
2 删除
3 输出
手写版本:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define LIST_INIT_SIZE 100
#define LIST_INCREMENT 10
using namespace std;
//带头节点版 头插法
struct ListNode
{
int val;
ListNode* next;
};
void Insert(ListNode* head, const int &pos, const int &num){
int cnt = 1;
ListNode* p = head->next;
while(p->next!=nullptr && cnt<pos){
p = p->next;
cnt++;
}
ListNode* tmp = (ListNode*)malloc(sizeof(ListNode));
tmp->val = num;
tmp->next = p->next;
p->next = tmp;
}
void Display(ListNode* head){
ListNode* p = head;
if(p->next == nullptr){
cout<<"list is empty!!!"<<endl;
return;
}
p = p->next;
while(p->next){
cout<<p->val<<" ";
p = p->next;
}
cout<<p->val<<endl;
}
void Delete(ListNode* head, int &pos){
int cnt = 1;
ListNode* p = head->next;
while(p->next!=nullptr && cnt<pos){
p = p->next;
cnt++;
}
p->next = p->next==nullptr ? nullptr:p->next->next;
}
//选择排序
void cSort(ListNode* head){
if(!head) return;
ListNode* h = head;
ListNode* m;
for(ListNode* i = h->next->next; i->next; i = i->next){
m = i;
ListNode* j;
for(j = i->next; j; j = j->next){
if(m->val > j->val) m = j;
}
int tmp;
if(m->val!=i->val){
tmp = i->val;
i->val = m->val;
m->val = tmp;
}
}
}
//逆转链表
void rever(ListNode* head){
ListNode* h = head;
ListNode* first = head->next;
ListNode* go = h->next->next;
while(go->next){
ListNode* tmp = go->next;
go->next = go->next->next;
tmp->next = first->next;
first->next = tmp;
}
}
int main()
{
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
ListNode* first = (ListNode*)malloc(sizeof(ListNode));
head->next = first;
first->next = nullptr;
int n, op;//操作次数,操作类型
cin>>n;
while(n--)
{
cin>>op;
switch(op)
{
case 1 :
int num, pos;
cin>>pos>>num;
Insert(head, pos, num);//如果想顺次插入,传入较大的pos即可
break;
case 2 :
cin>>pos;
Delete(head, pos);
break;
case 3 :
Display(head->next);
break;
default :
cout<<"no such operation!!!"<<endl;
break;
}
}
return 0;
}
STL版本:
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<list>
#define LIST_INIT_SIZE 100
#define LIST_INCREMENT 10
using namespace std;
int main()
{
list<int>l;
int n, op;//操作次数,操作类型
cin>>n;
list<int>::iterator it;
while(n--)
{
cin>>op;
switch(op)
{
case 1 :
int num, pos;
cin>>pos>>num;
it = l.begin();
while(--pos) it++;
l.insert(it, num);
break;
case 2 :
cin>>pos;
it = l.begin();
while(--pos) it++;
l.erase(it);
break;
case 3 :
for(auto i:l) cout<<i<<" ";
cout<<endl;
break;
default :
cout<<"no such operation!!!"<<endl;
break;
}
}
return 0;
}
/****************stl::list的其他用法***************/
//头部添加元素:l.push_front(const T& x);
//末尾添加元素:l.push_back(const T& x);
//任意位置插入 n 个相同元素:l.insert(iterator it, int n, const T& x);
//删除 [first,last] 之间的元素:l.erase(iterator first, iterator last);
//合并两个列表的元素(默认升序排列):lst.merge(lst1);
//在任意位置拼接入另一个list:lst.splice(iterator it, list&);
//删除容器中相邻的重复元素:lst.unique();
//删除所有大于10的数l.remove_if([](int n){ return n > 10; });
/****************注意事项***********/
//list 为双向迭代器,故不支持it+=i;
//list 不支持下标访问和at方法访问。