【发布时间】:2017-03-29 07:14:34
【问题描述】:
这是我的双向链表的代码。它工作正常。我需要帮助来排序这个链表的数据元素。
#include <stdio.h>
#include <stdlib.h>
struct Node{
int data;
struct Node* next;
struct Node* prev;
};
struct Node* head;//global variable
int GetNewNode(int x)
{
struct Node* newNode=(struct Node*)malloc(sizeof(struct Node));
newNode->data=x;
newNode->prev=NULL;
newNode->next=NULL;
return newNode;
}
int InsertAtHead(int x)
{
struct Node* newNode =GetNewNode(x);
if(head==NULL)//list empty
{
head=newNode;
return;
}
head->prev=newNode;
newNode->next=head;
head=newNode;
}
void print()
{
struct Node* temp=head;//start printing from head
printf("Forward: ");
while(temp!=NULL)
{
printf("%d ",temp->data);
temp=temp->next;
}
printf("\n");
}
int main()
{
head=NULL;// initially taking it as null
InsertAtHead(2);print();
InsertAtHead(5);print();
InsertAtHead(3);print();
InsertAtHead(9);print();
return 0;
}
我想在这里对数据元素进行排序。 我试过这个:
void sort()
{
struct Node* temp=head;
int numTemp;
while(temp!=NULL)
{
if(temp->prev > temp->next)
{
numTemp=temp->next;
temp->next= temp->prev;
temp->prev=numTemp;
}
}
}
但这比较的是地址,而不是链表的数据,我如何比较数据并相应地对它们进行排序?
【问题讨论】:
-
你访问数据...
temp->prev->data等等。只是不要取消引用任何 NULL 指针。
标签: c data-structures linked-list doubly-linked-list