考虑包含五个元素的链接列表。 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