[Data structure] doubly linked list

Source: Internet
Author: User

[CPP]View Plaincopy
    1. typedef struct node{
    2. struct NODE *fwd;
    3. struct NODE *bwd;
    4. int value;
    5. }node;

The bwd pointer of the root node of the doubly linked list points to the last node of the doubly linked list, the FWD pointer to the first node of the doubly linked list, and the value field of the doubly linked list as null

The following program inserts a value into an ordered double-linked list, and if a node already has the same value in the linked list, it is not inserted

[CPP]View Plaincopy
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. typedef struct node{
  4. struct NODE *bwd;
  5. struct NODE *fwd;
  6. int value;
  7. }node;
  8. BOOL Insert (Node *rootnode,int newvalue);
  9. BOOL Insert (Node *rootnode,int newvalue)
  10. {
  11. Node Temnode;
  12. int i = 0;
  13. Temnode = Rootnode;
  14. Node *newnode = (node*) malloc (sizeof (Node));
  15. if (newnode ==null)
  16. {
  17. printf ("malloc fail");
  18. return false;
  19. }
  20. Newnode->value = newvalue;
  21. if (rootnode->bwd = = NULL)
  22. {
  23. ROOTNODE->BWD = NewNode;
  24. ROOTNODE->FWD = NewNode;
  25. return true;
  26. }
  27. For (; TEMNODE->FWD! = Null;temnode = temnode->fwd)
  28. {
  29. i++;
  30. if (Temnode->value = = newvalue)
  31. {
  32. printf ("NewValue is already in double link list");
  33. return true;
  34. }
  35. if (Temnode->value > NewValue)
  36. {
  37. if (i==1)
  38. {
  39. NEWNODE->FWD = rootnode->fwd;
  40. ROOTNODE->FWD = NewNode;
  41. NEWNODE->BWD = Rootnode;
  42. newnode->fwd->bwd=newnode;
  43. }
  44. Else
  45. {
  46. Temnode = temnode->bwd;
  47. NEWNODE->FWD = temnode->fwd;
  48. TEMNODE->FWD = NewNode;
  49. NEWNODE->BWD = Temnode;
  50. newnode->fwd->bwd=newnode;
  51. }
  52. }
  53. Else
  54. {
  55. Temnode = temnode->bwd;
  56. NewNode = temnode->fwd;
  57. NEWNODE->BWD = Temnode;
  58. }
  59. }
  60. return true;
  61. }

[Data structure] doubly linked list

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.