Think: 每次进行插入相对应位置的元素,然后遍历输出。 过程: 第一次:1 第二次:1 2 第三次:3 1 2 第四次:3 1 2 4
Problem Description
给出一个只有头指针的链表和 n 次操作,每次操作为在链表的第 m 个元素后面插入一个新元素x。若m 大于链表的元素总数则将x放在链表的最后。 Input
多组输入。每组数据首先输入一个整数n(n∈[1,100]),代表有n次操作。 接下来的n行,每行有两个整数Mi(Mi∈[0,10000]),Xi。 Output
对于每组数据。从前到后输出链表的所有元素,两个元素之间用空格隔开。 Example Input
4 1 1 1 2 0 3 100 4 Example Output
3 1 2 4
#include<bits/stdc++.h> using namespace std; struct node { int data; struct node *next; }; int len; void creatlist(struct node *head, int m, int n); void display(struct node *head); int main() { int T; int n, m; while(cin >> T) { struct node *head; head = new node; len = 0; while(T --) { cin >> m >> n; creatlist(head,m, n); } display(head); } return 0; } void creatlist(struct node * head ,int m, int n) { struct node *p, *q; int i; p = head; for (i = 0;i < m && i < len;i ++) p = p -> next; q = new node; q -> data = n; q -> next = p -> next; p -> next = q; len ++; } void display(struct node *head) { struct node *q; q = head -> next; while(q) { cout << q -> data; if (q -> next == NULL) cout << endl; else cout << " "; q = q -> next; } }