考慮包含五個元素的鏈接列表。 1,2,3,4,5在兩個之後插入一個不是'7'。我們將會有一個頭指向鏈表和ptr的最後一個元素。當在3之前插入一個元素時,我們將從頭到尾循環遍歷鏈表,並且我們將引入另一個指針(prev)來保存先前的指針address.ptr將指向當前節點,並且如果找到匹配的數據(3 ),那麼我們必須包含2到3之間的新節點。 我們可以這樣做,因爲我們有先前的指針。如何做到這一點而不使用以前的指針。在鏈接列表中插入元素
編輯:
#include<stdio.h>
#include<stdlib.h>
struct list
{
int data;
struct list* link;
};
struct list *head=NULL;
struct list *tail=NULL;
void createList(int value);
void displayList(struct list* head_node);
void insertNewNode();
int value;
int main()
{
int i;
for(i=0;i<5;i++)
{
printf("\nEnter the data to be added into the list:\n");
scanf("%d",&value);
createList(value);
}
printf("\nCreated Linked list is\n");
//displayList(head);
printf("\nInsert a node\n");
insertNewNode();
displayList(head);
return 0;
}
void insertNewNode()
{
int val;
struct list* ptr=NULL,*new_node,*prev=NULL;
new_node = (struct list*)malloc(sizeof(struct list));
printf("Enter the data to be inserted!");
scanf("%d",&val);
for(ptr=head;ptr;ptr=ptr->link)
{
if(ptr->data == 3)
{
printf("Found");
new_node->data = val;
prev->link=new_node;
new_node->link = ptr;
}
prev = ptr;
}
}
void createList(int value)
{
struct list *newNode;
newNode = (struct list*)malloc(sizeof(struct list));
//tail = (struct list*)malloc(sizeof(struct list));
newNode->data = value;
if(head == NULL)
{
head = newNode;
}
else
{
tail->link = newNode;
}
tail = newNode;
tail->link = NULL;
}
void displayList(struct list *head_node)
{
struct list *i;
for(i=head;i;i=i->link)
{
printf("%d",i->data);
printf(" ");
}
printf("\n");
}
而不是試圖描述**你的當前代碼,爲什麼不只是發佈一些**實際**代碼? –
@Oli:我在這裏發佈了代碼。發佈的代碼不符合標準。 – Angus