当前位置:   article > 正文

数据结构C三双向链表_三向链表

三向链表

双链表是给链表中的每一个节点多加一个指针域,这个指针域将指向它的前驱,因此在双链表上,既方便查找后继,又方便查找节点的前驱。抄写并理解代码。

1.双向链表的存储,建立链表。

  1. typedef struct DoubleLinkedNode{
  2. char data;
  3. struct DoubleLinkedNode *previous;
  4. struct DoubleLinkedNode *next;
  5. }DLNode, *DLNodePtr;

2.双向链表初始化

  1. DLNodePtr initLinkList(){
  2. DLNodePtr tempHeader = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
  3. tempHeader->data = '\o';
  4. tempHeader->previous = NULL;
  5. tempHeader->next = NULL;
  6. return tempHeader;
  7. }

3.双向链表打印

  1. void printList(DLNodePtr paraHeader){
  2. DLNodePtr p = paraHeader->next;
  3. while (p != NULL){
  4. printf("%c",p->data);
  5. p = p->next;
  6. }
  7. printf("\r\n");
  8. }

4.双向链表按位插入元素

  1. void insertElement(DLNodePtr paraHeader,char paraChar,int paraPosition){
  2. DLNodePtr p,q,r;
  3. p = paraHeader;
  4. for(int i = 0;i < paraPosition; i ++){
  5. p = p->next;
  6. if(p == NULL) {
  7. printf("The position %d is beyond the scope of the list.",paraPosition);
  8. return;
  9. }
  10. }
  11. q = (DLNodePtr)malloc(sizeof(struct DoubleLinkedNode));
  12. q->data = paraChar;
  13. r = p->next;
  14. q->next = p->next;
  15. q->previous = p;
  16. p->next = q;
  17. if (r != NULL){
  18. r->previous = q;
  19. }
  20. }

5.删除指定元素

  1. void deleteElement(DLNodePtr paraHeader, char paraChar){
  2. DLNodePtr p,q,r;
  3. p = paraHeader;
  4. while((p->next != NULL) && (p->next->data != paraChar)){
  5. p = p->next;
  6. }
  7. if(p->next == NULL){
  8. printf("The char'%c' does not exist.\r\n",paraChar);
  9. return;
  10. }
  11. q = p->next;
  12. r = q->next;
  13. p->next = r;
  14. if(r != NULL) {
  15. r->previous = p;
  16. }
  17. free(q);
  18. }

6.插入元素,测试操作

  1. void insertDeleteTest(){
  2. DLNodePtr tempList = initLinkList();
  3. printList(tempList);
  4. insertElement(tempList, 'H',0);
  5. insertElement(tempList, 'e',1);
  6. insertElement(tempList, 'l',2);
  7. insertElement(tempList, 'l',3);
  8. insertElement(tempList, 'o',4);
  9. insertElement(tempList, '!',5);
  10. printList(tempList);
  11. deleteElement(tempList, 'e');
  12. deleteElement(tempList, 'a');
  13. deleteElement(tempList, 'o');
  14. printList(tempList);
  15. }

7.地址的显示

  1. void basicAddressTest(){
  2. DLNode tempNode1, tempNode2;
  3. tempNode1.data = 4;
  4. tempNode1.next = NULL;
  5. tempNode2.data = 6;
  6. tempNode2.next = NULL;
  7. printf("The first node: %d, %d, %d\r\n",
  8. &tempNode1, &tempNode1.data, &tempNode1.next);
  9. printf("The second node: %d, %d, %d\r\n",
  10. &tempNode2, &tempNode2.data, &tempNode2.next);
  11. tempNode1.next = &tempNode2;
  12. }

8.运行结果

 9.理解图示

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/655463
推荐阅读
相关标签
  

闽ICP备14008679号