Single list - Template title

826. singly linked list  

Achieve a single linked list is initially empty, supports three operations:

(1) a number to the list head insert;

(2) deleting the k-th number of digits after insertion;

(3) inserting a number in the k-th number of inserted

Now, after M times to operate the chain, complete all operations, the output of the entire list from beginning to end.

Note : k-th title number does not refer to the insertion of the k number of the current list. During operation, for example, a total of n number is inserted, the insert according to the chronological order, the order of the n number of: inserting a first number, the second number is inserted, ... n-th number of insertion.

Input Format

The first row contains an integer M, it represents the number of operations.

Next M rows, each row comprising an operation command, an operation command may be as following:

(1) "H x", x denotes a number from the list is inserted into the head.

(2) "D k", represents the number of deleted behind the k-th input number (when k is 0, means to delete the first node).

(3) "I kx", inserting a number x indicates the number of the input after the k-th (k in this operation are greater than 0).

Output Format

Total row, the entire chain from beginning to end output.

data range

1 M 100000 1≤M≤100000
all operations to ensure legal.

Sample input:

10
H 9
I 1 1
D 1
D 0
H 6
I 3 6
I 4 5
I 4 5
I 3 4
D 6

Sample output:

6 4 6 5

#include<iostream>

using namespace std;


const int N = 1e5 + 50;
int head,e[N],ne[N],idx;
void init(){
	head = -1;
	idx = 0;
}
void head_add(int x){
	e[idx] = x;
	ne[idx] = head;
	head = idx++;
}
void d_k(int k){
	ne[k] = ne[ne[k]]; 
}
void add_k(int k,int x){
	e[idx] = x;
	ne[idx] = ne[k];
	ne[k] = idx++;
}

int main(){
    int m,k;
    int n;
	scanf("%d",&m);
	char op[2];
	init();
	while(m --){
		scanf("%s",op);
		if(op[0] == 'H'){
			scanf("%d",&n);
			head_add(n);
		}else if(op[0] == 'D'){
			scanf("%d",&k);
			if(!k) head = ne[head];
			else d_k(k - 1);
		}else {	
			scanf("%d%d",&k,&n);
			add_k(k - 1,n);
		}
	}
	for(int i = head;i != -1;i = ne[i]) printf("%d ",e[i]);
    return 0;
}

  

 

Guess you like

Origin www.cnblogs.com/luyuan-chen/p/11495255.html