分数 20
作者 伍建全
单位 重庆科技大学
You are required to implement a function with the prototype(函数原型) void insert(List L, int val, int key)
. The function’s purpose is to insert a new node with data field value key
after the node in the linked list L
that has a data field equal to val
. If no node with data value equal to val
is found in the linked list, the new node should be inserted at the end of the list.
Structure description:
The node structure is shown below:
typedef struct ListNode {
int data;
struct ListNode *next;
} node;
typedef node* position;
typedef position List;
Function definition:
void insert(List L, int val, int key);
The parameter L
is a pointer to the dummy header. The function inserts a new node with data field equal to key after the node in linked list L whose data field is equal to val. If there is no node with data field equal to val, the function inserts the new node with data field key at the end of the list.
Test program example:
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int data;
struct ListNode *next;
}node;
typedef node* position;
typedef position List;
void insert(List L, int val, int key);
// The questioner has implemented the createList function.
// This function reads a series of positive integers separated by spaces
// and inserts them into a linked list using the head insertion method.
// Entering -1 indicates the end of input.
// creatgeList函数由题目提供,不需要在本题的答案中实现
List createList();
//Function show outputs the data field of each node in the linked list L.
// show函数由题目提供,不需要在本题的答案中实现
void show(List L);
int main(void)
{
List L = createList();
show(L);
int val, key;
scanf("%d%d", &val, &key);
insert(L, val, key);
show(L);
return 0;
}
Input Specification:
There are two lines of input. The first line is a series of positive integers, and entering -1 indicates the end of the input. We agree that all input numbers are different. (我们约定所有的输入不会出现重复的数值)The second line contains two integers, val and key. This represents that a node with a data field equal to key should be inserted after the node in the linked list where the data field is equal to val.
Output Specification:
Output the data field of each node in the singly linked list. After each number, output a space.(每个整数后输出1个空格)
Sample Input :
10 20 30 40 50 -1
30 9
Sample Output :
50 40 30 20 10
50 40 30 9 20 10
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
C程序如下:
void insert(List L, int val, int key){
node*newnode = (node*)malloc(sizeof(node));//创建新结点
newnode->data = key;//给新结点的数据域赋值
newnode->next = NULL;//初始化新结点的next域指针
node *p = L;//定义一个新指针指向该单链表的头结点
while(p->next != NULL){// 遍历链表,查找值为val的节点
if(p->data == val){// 检查是否找到了值为val的节点
newnode->next = p->next;// 插入新节点到值为val的节点之后
p->next = newnode;
return;
}
p = p->next;
}
p->next = newnode;// 如果没有找到值为val的节点则插入该链表的末尾
}