单链表
对于没有固定头结点的单链表实现方法
#include <iostream>
using namespace std;
int head, v[100010], ne[100010], idx = 0;
void init()
{
head = -1;
idx = 0;
}
void insert_head(int x)
{
ne[idx] = head;
head = idx;
v[idx] = x;
idx++;
}
void insert(int k, int x)
{
v[idx] = x;
ne[idx] = ne[k];
ne[k] = idx;
idx++;
}
void del(int k)
{
ne[k] = ne[ne[k]];
}
void show()
{
int i = head;
while(i != -1){
cout << v[i] << " ";
i = ne[i];
}
}
int main()
{
int n, k, x;
cin >> n;
init();
for(int i = 0; i < n; i ++){
char c;
cin >> c;
if(c == 'H'){
cin >> x;
insert_head(x);
}else if(c == 'D'){
cin >> k;
if(k){
del(k - 1);
}else{
head = ne[head];
}
}else if(c == 'I'){
cin >> k >> x;
insert(k - 1, x);
}
}
show();
return 0;
}
伪头结点单链表实现方法,即用a[0]作为一个固定的头结点。
#include <iostream>
using namespace std;
int v[100010], ne[100010], idx;
void init()
{
idx = 1;
}
void insert(int k, int x)
{
v[idx] = x;
ne[idx] = ne[k];
ne[k] = idx;
idx++;
}
void del(int k)
{
ne[k] = ne[ne[k]];
}
void show()
{
int i = ne[0];
while(i){
cout << v[i] << " ";
i = ne[i];
}
}
int main()
{
int n, k, x;
cin >> n;
init();
for(int i = 0; i < n; i ++){
char c;
cin >> c;
if(c == 'H'){
cin >> x;
insert(0, x);
}else if(c == 'D'){
cin >> k;
del(k);
}else if(c == 'I'){
cin >> k >> x;
insert(k, x);
}
}
show();
return 0;
}
基于cpp的面向对象设计
class MyLinkedList {
public:
MyLinkedList() {
idx = 0;
head = -1;
}
int get(int index) {
int t = head;
if(t == -1){
return -1;
}
for(int i = 0; i < index; i ++){
if(ne[t] != -1){
t = ne[t];
}else{
return -1;
}
}
return v[t];
}
void addAtHead(int val) {
v[idx] = val;
ne[idx] = head;
head = idx++;
}
void addAtTail(int val) {
int t = head;
if(t == -1){
addAtHead(val);
return;
}
while(ne[t] != -1){
t = ne[t];
}
v[idx] = val;
ne[idx] = -1;
ne[t] = idx++;
}
void addAtIndex(int index, int val) {
int t = head;
if(index == 0){
addAtHead(val);
show();
return ;
}
if(t == -1){
return;
}
for(int i = 0; i < index - 1; i ++){
if(ne[t] != -1){
t = ne[t];
}else{
return;
}
}
v[idx] = val;
show();
ne[idx] = ne[t];
ne[t] = idx++;
}
void deleteAtIndex(int index) {
int t = head;
if(t == -1){
return ;
}
if(index == 0 ){
head = ne[head];
return;
}
for(int i = 0; i < index - 1; i ++){
if(ne[t] != -1){
t = ne[t];
}else{
return ;
}
}
if(ne[t] != -1){
ne[t] = ne[ne[t]];
}
}
void show(){
int t = head;
while(t != -1){
cout << v[t] << " ";
t = ne[t];
}
cout << endl;
}
private:
int idx = 0;
int head = -1;
int v[10000];
int ne[10000];
};