1.问题提出
2.问题分析
3解决问题
4.得出结果
一.问题提出
输入了一个长度为 n 的数组,把这个数组转换成链表并在第 i 个节点的后面添加一个值为 i 的新节点
二.问题分析
第一行输入两个正整数,一个表示数组的长度,另外一个表示需要添加节点的位置和所要插入值
第二行输入 数组元素值
三.解决问题
链表的结构体设计
typedef int ELEM_TYPE;
typedef struct Node {
ELEM_TYPE data;
struct Node* next;
}Node, * PNode;
初始化
void Init_Node(PNode p) {
p->next = NULL;
}
插入元素---尾插法
void Insert(PNode p, ELEM_TYPE val)
{
struct Node* q = (struct Node*)malloc(1 * sizeof(struct Node));
assert(q != NULL);
q->data = val;
struct Node* n = p;
for (; n->next != NULL; n = n->next);
q->next = n->next;
n->next = q;
}
因为刚开始要将数组元素输入链表当中,可以使用头插,他的时间复杂度为O(1),小白这里用的是尾插法,大家可以试试头插法。
按位置插
void insert_pos(PNode p, int pos, int val) {
struct Node* q = (struct Node*)malloc(1 * sizeof(struct Node));
assert(q != NULL);
q->data = val;
struct Node* n= p;
for (int i = 0; i < pos; i++) {
n = n->next;
}
q->next = n->next;
n->next = q;
}
这块的目的主要是将要目标插入位置和值获取到链表中,即就是按位置插。
打印元素
void Show(PNode p) {
struct Node* q = p->next;
for (; q != NULL; q = q->next) {
printf("%d ", q->data);
}
}
测试案例
int main() {
struct Node head;
Init_Node(&head);
int arr[1024] = { 0 };
int s = 0,i=0;
scanf("%d %d", &s,&i);
for (int i = 0; i < s; i++) {
scanf("%d", &arr[i]);
}
for (int i = 0; i < s; i++) {
Insert(&head, arr[i]);
}
int val = i;
insert_pos(&head, i, val);
Show(&head);
}
这里注意,测试函数应当注意数组的定义,如果大家使用java就用动态初始化数组,小白的C语言不是很好,就只能这么初始化数组,大家也可以试试宏定义。
得到结果
输入
5 3
5 4 3 2 1
结果
5 4 3 3 2 1
下面这个系列,是小白最近刷题所得,以上代码有什么疑惑可以去小白单链表那节去看看,上面所述代码均出现。继续努力,小白争取融会贯通这部分的内容。