gpt4 book ai didi

c - 单链表头尾法?

转载 作者:行者123 更新时间:2023-11-30 18:11:01 24 4
gpt4 key购买 nike

我对 C 编程语言相对较新,并且正在尝试熟悉它,但我不确定如何使用我正在尝试执行的以下结构和数据实际实现链表(如下) )。基本上,目标是从带有头和尾的单链表中添加一个项目。

更新:我尝试在添加函数中编写一些代码,尚未对其进行排序,但它看起来是这样的吗?

代码来源

typedef struct {
char car_model[32],car_name[32];

} CarObjects;

typedef struct myNode{

struct myNode* next;
CarObjects* data;

} MyList;

//initialize list
void declareList(MyList* someList){
someList->next = NULL;
}

void insertElementByTitle(MyList* someList, CarObjects* someCar){

//first case adding to an empty list.
if(someList == NULL){
someList = malloc(sizeof(MyList));
someList->data = someCar;
someList->next = NULL;
}
//END OF first case adding to an empty list.

//make thee list's head and tail node, point to the first element since its an empty list
someList->head = someList;
someList->tail = someList->head;


while(someList->next != NULL)
someList = someList->next;

someList->next = malloc(sizeof(MyList));
someList = someList->next;
someList->data = newBook;
someList->next = NULL;


}


int main(){


MyList* listHead= NULL;
MyList* listTail= NULL;


//Somehow add an element to the list



return 0;
}

最佳答案

首先正确定义您的结构。

typedef struct car{
char car_model[32],car_name[32];
};

typedef struct myList{
myList * next;
car * carObject;
};

现在,您正在尝试使用插入排序技术进行插入。

void insertElementByTitle(MyList* someList, CarObjects* someCar){
\\I assume someList is pointing the head of the linked list
\\One more assumption that, the Linked List is already sorted and need to inset
\\someCar in the correct position.
MyList *secondPointer = someList->next;
while(secondPointer != null)
{
if(ifCarIsInBetweenSomeListAndSecondPointer(someList,secondPointer,someCar))
{
someList->next = newNode(someCar);
someList->next->next=secondPointer;
break;
}
someList = secondPointer; secondPointer = secondPointer->next;
}
if(secondPointer == null)
{
someList->next = newNode(someCar);
}
}

现在,您需要两个函数

myNode* newNode(car * someCar);
bool ifCarIsInBetweenSomeListAndSecondPointer(myNode *someList,myNode *secondPointer,car *someCar);

myNode* newNode(car * someCar){
myNode * t =(struct myNode*)malloc(sizeof(struct myNode));
t->carObject = someCar;
t->next= null;
return t;
}

bool ifCarIsInBetweenSomeListAndSecondPointer(myNode *someList,myNode *secondPointer,car *someCar){
if( (strcmp(someList->carObject->car_name,someCar->carObject)<0) &&(strcmp(someCar->carObject,secondPointer->carObject->car_name)<0))
return true;
return false;
}

引用在线引用,例如geeksforgeeks-linked list ,以获得更好的理解。

关于c - 单链表头尾法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52975975/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com