链表的插入时间限制:1秒 内存限制:128M题目描述给定一个链表对链表进行插入操作最后顺序输出链表输入描述第一行一个整数n2=n=1000000代表初始链表中的元素。第二行含n个整数tint范围表示链表的每一个结点的值链表前面指向后面。第三行一个数m1=m n 代表要插入的结点的数量。第4~m+3行每行两个整数x和y2=xny是int范围代表从第x个输入的数后面插入一个结点结点的值是
// 思路: // 1. 根据输入构建初始链表 // 2. 根据插入操作,在链表中插入新节点 // 3. 顺序输出链表中的元素
#include
using namespace std;
class ListNode { public: int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} };
// 构建初始链表
ListNode* buildLinkedList(vector
// 在链表中插入新节点 ListNode* insertNode(ListNode* head, int x, int y) { ListNode* dummy = new ListNode(-1); dummy->next = head; ListNode* cur = dummy; while (cur->next && x > 1) { cur = cur->next; x--; } ListNode* newNode = new ListNode(y); newNode->next = cur->next; cur->next = newNode; return dummy->next; }
// 顺序输出链表中的元素 void printLinkedList(ListNode* head) { ListNode* cur = head; while (cur) { cout << cur->val << " "; cur = cur->next; } cout << endl; }
int main() {
int n;
cin >> n;
vector
int m;
cin >> m;
for (int i = 0; i < m; i++) {
int x, y;
cin >> x >> y;
head = insertNode(head, x, y);
}
printLinkedList(head);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/jahX 著作权归作者所有。请勿转载和采集!