双向链表中如果有了头结点和尾结点,对于头插法和尾插法就显得非常方便。这样在尾部插入一个元素也就不用去遍历链表了。个人建议使用这种链表来处理问题。代码上传至 https://github.com/chenyufeng1991/HeadInsertAndTailInsert_DoubleList_HeadList 。
核心代码如下:
//创建带头结点和尾结点的双向非循环链表(头插法)
void HeadInsertCreateList(Node *pHead,Node *pTail){
Node *pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
while (pInsert->element > 0) {
pHead->next->prior = pInsert;
pInsert->next = pHead->next;
pInsert->prior = pHead;
pHead->next = pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
}
printf("%s函数执行完成,头插法建立带头节点和尾结点的双向非循环链表创建成功\n",__FUNCTION__);
}
//创建带头结点和尾结点的双向非循环链表(尾插法)
void TailInsertCreateList(Node *pHead,Node *pTail){
Node *pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
while (pInsert->element > 0) {
pTail->prior->next = pInsert;
pInsert->prior = pTail->prior;
pInsert->next = pTail;
pTail->prior = pInsert;
pInsert = (Node *)malloc(sizeof(Node));
memset(pInsert, 0, sizeof(Node));
pInsert->prior = NULL;
pInsert->next = NULL;
scanf("%d",&(pInsert->element));
}
printf("%s函数执行完成,尾插法建立带头节点和尾结点的双向非循环链表创建成功\n",__FUNCTION__);
}
测试代码如下:
int main(int argc, const char * argv[]) {
Node *pHead;//头结点
Node *pTail;//尾结点
InitialList(&pHead, &pTail);
HeadInsertCreateList(pHead, pTail);
PrintList(pHead, pTail);
TailInsertCreateList(pHead, pTail);
PrintList(pHead, pTail);
return 0;
}