我一直在研究一组用于双向链表的函数,我遇到的一个问题是将元素插入到列表中但保持列表的排序顺序。所以如果我有一个 {3, 4, 6} 列表并插入 5 那么列表将变为 {3, 4, 5, 6}
我昨晚重写后刚刚完成了最新的代码,请评论告诉我是否有更好的方法,我同时发布头文件和c文件。我要指出的一件事是,我不使用指向当前节点的指针,而只在插入函数中创建一个指针,该指针创建一个具有临时位置的新节点。
列表.H
/* custom types */
typedef struct node
{
int val;
struct node * next;
struct node * prev;
}Node;
typedef struct list
{
Node * head;
Node * tail;
}List;
/* function prototypes */
/* operation: creates a list */
/* pre: set equal to a pointer to a list*/
/* post: list is initialized to empty */
List* NewList();
/* operation: Insert a number into a list sorted */
/* pre: plist points to a list, num is an int */
/* post: number inserted and the list is sorted */
void Insert(List * plist, int x);
列表.C
/* c file for implentation of functions for the custome type list */
/* specifically made for dueling lists by, Ryan Foreman */
#include "List.h"
#include <stdlib.h> /* for exit and malloc */
#include <stdio.h>
List* NewList()
{
List * plist = (List *) malloc(sizeof(List));
plist->head = NULL;
plist->tail = NULL;
return plist;
}
void Insert(List * plist, int x)
{
/* create temp Node p then point to head to start traversing */
Node * p = (Node *) malloc(sizeof(Node));
p->val = x;
/* if the first element */
if ( plist->head == NULL) {
plist->head = p;
plist->tail = p;
}
/* if inserting into begining */
else if ( p->val < plist->head->val ) {
p->next = plist->head;
plist->head->prev = p;
plist->head = p;
}
else {
p->next = plist->head;
int found = 0;
/* find if there is a number bigger than passed val */
while((p->next != NULL) && ( found == 0)) {
if(p->val < p->next->val)
found = 1;
else {
p->next = p->next->next;
}
}
/* if in the middle of the list */
if(found == 1)
{
p->prev = p->next->prev;
p->next->prev = p;
}
/* if tail */
else {
plist->tail->next = p;
p->prev = plist->tail;
plist->tail = p;
}
}
}
感谢您对代码的任何输入,感谢您的任何评论