题目描述
建立长度为n的单链表,在第i个结点之前插入数据元素data。
输入
第一行为自然数n,表示链式线性表的长度; 第二行为n个自然数表示链式线性表各元素值; 第三行为指定插入的位置i;第四行为待插入数据元素data。
输出
指定插入位置合法时候,输出插入元素后的链式线性表的所有元素,元素之间用一个空格隔开。输入不合法,输出"error!"。
样例输入
5 1 2 3 4 5 3 6样例输出
1 2 6 3 4 5#include<stdio.h> #include<string.h> #include<math.h> #include<malloc.h> #define INF 0x3f3f3f3f #define MAX(x,y) (x>y?x:y) #define MIN(x,y) (x>y?y:x) #define M 10001 int flag = 1; typedef struct LNode { int data; struct LNode* next; }LNode; void printfLNode(LNode* L) { LNode* temp = L; while (temp->next) { temp = temp->next; printf("%d ", temp->data); } } int insertLNode(LNode* L, int m, int x) { int i = 0; LNode* temp = L; while (temp && i < m - 1) { temp = temp->next; i++; } if (!temp || i > m - 1) { printf("error!"); return 0; } LNode* p = (LNode*)malloc(sizeof(LNode)); p->data = x; p->next = temp->next; temp->next = p; return 1; } int main() { LNode* L; L = (LNode*)malloc(sizeof(LNode)); int n; scanf("%d", &n); L->next = NULL; LNode* temp = L; for (int i = 0; i < n; i++) { LNode* p = (LNode*)malloc(sizeof(LNode)); scanf("%d", &p->data); p->next = NULL; temp->next = p; temp = p; } int m, x; scanf("%d%d", &m, &x); int h=insertLNode(L, m, x); if (h == 1) { printfLNode(L); } return 0; }
SWUST OJ952: 单链表的插入操作的实现
最新推荐文章于 2023-10-12 22:31:19 发布