Data structures 在排序的双链接列表中插入节点
在双排序链表中插入节点每次插入后,应对列表进行排序 节点定义为Data structures 在排序的双链接列表中插入节点,data-structures,insert,linked-list,doubly-linked-list,sortedlist,Data Structures,Insert,Linked List,Doubly Linked List,Sortedlist,在双排序链表中插入节点每次插入后,应对列表进行排序 节点定义为 struct Node { int data; Node *next; Node *prev; } 下面是函数的逻辑 Node* SortedInsert(Node *head,int data) { // Complete this function // Do not write the main method. struct Node *newn= (stru
struct Node
{
int data;
Node *next;
Node *prev;
}
下面是函数的逻辑
Node* SortedInsert(Node *head,int data)
{
// Complete this function
// Do not write the main method.
struct Node *newn= (struct Node*)malloc(sizeof(struct Node*));
newn->data= data;
newn->next= newn->prev= NULL;
struct Node *trav=head, *pre=NULL;
if(head==NULL)
head= newn;
else if(newn->data <= trav->data)
{
newn->next= trav;
trav->prev= newn;
head= newn;
}
else
{
while(trav->data <= newn->data)
{
pre= trav;
trav=trav->next;
}
pre= trav;
trav=trav->next;
newn->next= trav;
trav->prev= newn;
pre->next= newn;
newn->prev= pre;
}
return head;
}
Node*SortedInsert(Node*head,int数据)
{
//完成此功能
//不要编写main方法。
结构节点*newn=(结构节点*)malloc(sizeof(结构节点*);
新建->数据=数据;
newn->next=newn->prev=NULL;
结构节点*trav=head,*pre=NULL;
if(head==NULL)
头=新;
else if(新建->数据)
{
newn->next=trav;
trav->prev=newn;
头=新;
}
其他的
{
while(trav->data)
{
pre=trav;
trav=trav->next;
}
pre=trav;
trav=trav->next;
newn->next=trav;
trav->prev=newn;
pre->next=newn;
newn->prev=pre;
}
回流头;
}
请告诉我逻辑有什么问题您犯了一个小错误,首先空间是这样分配的:
struct Node *newn= (struct Node*)malloc(sizeof(struct Node));
正确的条件是:
else
{
while(trav!=NULL&&trav->data <= newn->data)
{
pre= trav;
trav=trav->next;
}
newn->prev=pre;
newn->next=trav;
pre->next=newn;
if(trav!=NULL)
trav->prev=newn;
}
else
{
while(trav!=NULL&&trav->data)
{
pre=trav;
trav=trav->next;
}
newn->prev=pre;
newn->next=trav;
pre->next=newn;
如果(trav!=NULL)
trav->prev=newn;
}