typedef struct Element
{
int number;
struct Element *right;
struct Element *left;
} Element;
Element *newElement;
Element *head;
Element *pos;
Element *current;
void insert_Element()
{
newElement = malloc(sizeof(Element));
if (head==NULL)
{
head = newElement;
current = newElement;
current->right = pos;
//pos->left = current;
}
}
双链表的头应该有一个指向下一个(right
(元素的指针(它是NULL
,但也是pos
(。这很好,但从pos
/NULL
返回的指针(left
(不起作用。我做了什么工作;这可能吗?提前感谢:(
当前版本的insert_Element
函数不起作用,除非head
是NULL
,而pos
不是NULL
,并且它不会设置新元素的left
成员。pos
变量的用途尚未说明,但似乎用于指向要插入新元素的元素。我们可以使用pos == NULL
来指示新元素将被放置在列表的末尾。这里有一个版本可以做到这一点:
void insert_Element(void)
{
newElement = malloc(sizeof(Element));
if (newElement == NULL)
{
return;
}
newElement->right = pos;
if (pos != NULL)
{
/* insert before pos */
newElement->left = pos->left;
pos->left = newElement;
}
else if (head != NULL)
{
/* add to end of list */
current = head;
while (current->right != NULL)
{
current = current->right;
}
newElement->left = current;
current->right = newElement;
}
else
{
/* add to empty list */
newElement->left = NULL;
}
if (pos == head)
{
/* make it the start of the list */
head = newElement;
}
/* make it the 'current' element */
current = newElement;
}
最好不要过多地使用全局变量,而是使用函数参数。这里有一个版本,它不使用全局变量,并返回一个指向列表上新元素的指针(或分配失败时的NULL
(:
Element *insert_Element(Element **phead, Element *pos)
{
Element *newElement = malloc(sizeof(Element));
if (newElement == NULL)
{
return NULL;
}
newElement->right = pos;
if (pos != NULL)
{
/* insert before pos */
newElement->left = pos->left;
pos->left = newElement;
}
else if (*phead != NULL)
{
/* add to end of list */
Element *current = *phead;
while (current->right != NULL)
{
current = current->right;
}
newElement->left = current;
current->right = newElement;
}
else
{
/* add to empty list */
newElement->left = NULL;
}
if (pos == *phead)
{
/* make it the start of the list */
*phead = newElement;
}
return newElement;
}
您可能只需要分配Element *pos
。事实上,pos等于NULL,逻辑上没有向左或向右的指针,这就像在一个不存在的房子里寻找厕所。