链接列表:如何对双向链表进行排序?

时间:2017-03-29 07:14:34

标签: c data-structures linked-list doubly-linked-list

这是我的双向链表的代码。它工作正常。我需要帮助排序此链表的数据元素。

#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;
    }
}
}

但这会比较地址,而不是链表的数据,如何比较数据并对其进行相应排序?

1 个答案:

答案 0 :(得分:1)

head结构中的

nextprecNode是指针,因此,它们只会指向相应的节点,方式与{{1 (在temp函数中)是指向当前正在访问的节点的指针。

要访问sort()指向的data节点,您将执行temp。同样,如果您想访问下一个节点的数据(地址为temp->data),您将执行temp->next

看来,迭代链表也存在问题。 要在链表中向前迭代,必须使temp->next->data指向下一个节点。

temp

这是你可以遍历列表的方法。