Description
Please write a program to first create a linked list. Then, based on the user's input, add the number "val" into the "place"-th position and directly print the result after addition.
請撰寫一支程式,先建立一個鏈結串列,接著根據使用者的輸入,將數字 val 新增到第 place個位置,並直接印出新增後的結果。
For example, original state: 2->3->7
例如:原始狀態:2->3->7
Add 5 into the 1st position, it will become: 5->2->3->7
新增 5 到第 1 個位置,會變成:5->2->3->7
Add 9 into the 3rd position, it will become: 5->2->9->3->7
新增 9 到第 3 個位置,會變成:5->2->9->3->7
Input
The first line contains multiple integers separated by spaces, terminated by -1, indicating the initial state of the linked list.
第一行輸入包含多個整數,以 -1 作為結束,代表一開始 Linked List 的狀態。
From the second line, there are multiple lines of input. Each line contains two numbers: "val" and "place" until EOF. There will be no situation where "place" is greater than the original number of nodes + 1.
第二行開始有多行輸入,每行有兩個數字:val 與 place。不會出現 place > 原節點個數+1 的情況。直到 EOF 為止。
Output
Please print the result after each addition of a number.
請印出每次新增數字後的結果。
Sample Input 1
2 3 7 -1
5 1
9 3
-17 5
Sample Output 1
5->2->3->7
5->2->9->3->7
5->2->9->3->-17->7
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int data;
struct node* next;
} Node;
// Function to insert a new node at a specific position
Node* InsertAtPosition(Node* head, int val, int place) {
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = val;
// If position is 1 or list is empty, insert at the beginning
if (place == 1 || head == NULL) {
new_node->next = head;
return new_node;
}
Node* current = head;
int count = 1;
// Traverse until position - 1
while (count < place - 1 && current->next != NULL) {
current = current->next;
count++;
}
// Insert the new node
new_node->next = current->next;
current->next = new_node;
return head;
}
// Function to print the linked list
void PrintList(Node* head) {
while (head != NULL) {
printf("%d", head->data);
if (head->next != NULL) {
printf("->");
}
head = head->next;
}
printf("\\n");
}
int main() {
int num, place;
Node* head = NULL;
// Creating the linked list from input
while (scanf("%d", &num) != EOF) {
if (num == -1)
break;
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = num;
new_node->next = NULL;
if (head == NULL)
head = new_node;
else {
Node* current = head;
while (current->next != NULL) {
current = current->next;
}
current->next = new_node;
}
}
// Inputting values and positions and inserting into the list
while (scanf("%d %d", &num, &place) != EOF) {
head = InsertAtPosition(head, num, place);
PrintList(head);
}
// Freeing allocated memory
Node* temp;
while (head != NULL) {
temp = head;
head = head->next;
free(temp);
}
return 0;
}