DLLInsert()中的逻辑错误 - 双链表

时间:2018-03-19 16:00:31

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

我在检查位置是否可用时遇到问题。 DLL节点的结构是:

struct DLLNode{
int data;
struct DLLNode * head;
struct DLLNode * prev;
};

指向DLL头部的指针声明为struct DLLNode * head ={0 , NULL , NULL}; 插入功能如下:

void DLLInsert(struct DLLNode **head, int data, int position) {
int k = 1;
struct DLLNode *temp, *newNode;
newNode = (struct DLLNode *) malloc(sizeof ( struct DLLNode ));
if(!newNode) { //Always check for memory errors
 printf (“Memory Error”);
 return;
}
newNode→data = data;
if(position == 1) { //Inserting a node at the beginning
 newNode→next = *head;
 newNode→prev = NULL;
 if(*head) 
 (*head)→prev = newNode;
 *head = newNode;
 return;
}
temp = *head;
while ( (k < position – 1) && temp→next!=NULL) {
 temp = temp→next;
 k++;
}
if(k!=position){
 printf("Desired position does not exist\n");
}
newNode→next=temp→next;
newNode→prev=temp;
if(temp→next)
 temp→next→prev=newNode;
 temp→next=newNode;
return;
 }

请检查检查可用位置的逻辑。 注意:列表未排序

0 个答案:

没有答案