#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
void insertAtFront(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
temp->next = head;
head = temp;
return ;
}
void displayAll()
{
struct Node* temp = head;
while(temp != NULL)
{
printf("%d\t",temp->data);
temp = temp->next;
}
printf("\n");
}
void insertAtNthPostion(int data,int key)
{
int i;
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
struct Node* temp1 = head;
for(i=1;i<key;i++)
temp1 = temp1->next;
temp->next = temp1->next;
temp1=temp;
displayAll();
return;
}
int main()
{
int num, i, data, key;
head= NULL;
printf("\nHow many data u want to insert? ");
scanf("%d", &num);
for(i=0; i < num; i++)
{
printf("\nEnter the data u want to insert:");
scanf("%d", &data);
insertAtFront(data);
}
displayAll();
printf("Enter the data and position u want to insert:\n");
scanf("%d%d", &data, &key);
insertAtNthPostion(data,key);
return 0;
}
我已经尝试过这个实现但是值没有改变,我的输出显示如下:
Enter the data u want to insert:
5
5 3 2 1 2
Enter the data and position u want to insert:
265498
2
5 3 2 1 2
答案 0 :(得分:0)
您需要将上一个节点->next
设置为新节点。
您还忘记了for循环{}
上的花括号。
您也忘记删除原始节点,但这不会改变结果,但会浪费内存..
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node* next;
};
struct Node* head;
void insertAtFront(int data)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = data;
temp->next = NULL;
temp->next = head;
head = temp;
return ;
}
void displayAll()
{
struct Node* temp = head;
while(temp != NULL)
{
printf("%d\t",temp->data);
temp = temp->next;
}
printf("\n");
}
void insertAtNthPostion(int data,int key)
{
int i;
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = data;
new_node->next = NULL;
struct Node* current = head;
struct Node* previous = NULL;
struct Node* temp = NULL;
for(i=1;i<key;i++) {
previous = current;
current = current->next;
}
new_node->next = current->next;
if (previous != NULL)
previous->next = new_node;
else
head = new_node;
free(current); //Release the old node's memory
displayAll();
return;
}
int main()
{
int num, i, data, key;
head= NULL;
printf("\nHow many data u want to insert? ");
scanf("%d", &num);
for(i=0; i < num; i++)
{
printf("\nEnter the data u want to insert:");
scanf("%d", &data);
insertAtFront(data);
}
displayAll();
printf("Enter the data and position u want to insert:\n");
scanf("%d%d", &data, &key);
insertAtNthPostion(data,key);
return 0;
}
虽然更好的解决方案是更改所选节点的数据,但不创建新节点:
void insertAtNthPostion(int data,int key)
{
struct Node* current = head;
int i;
for(i=1;i<key;i++) {
current = current->next;
}
current->data = data;
displayAll();
}
任何一种方法的结果都会给你:
Enter the data u want to insert:3
3 2 1
Enter the data and position u want to insert:
4
1
4 2 1