使用 C++ 程式設計實現已排序的迴圈單鏈表


在資料結構中,連結串列是一個線性資料集合。列表中的每個元素或節點包括兩項 - 資料和對下一個節點的引用。最後一個節點引用空。連結串列中的入口點稱為列表頭。

在單鏈表中,列表中的每個節點都儲存一個單鏈表中的內容和一個指標或引用,以引用列表中的下一個節點。單鏈表不儲存任何指向或引用上一個節點的指標。

由於它是一個已排序的單鏈表,因此連結串列中的資料項將始終保持排序。

這裡有一個 C++ 程式來實現已排序的迴圈單鏈表

演算法

Begin
   function createnode() to insert node in the list:
      It checks whether the list is empty or not. If the list is empty put the node as first element and update head.
      If list is not empty,
      It creates a newnode and inserts the number in the data field of the newnode.
      Now the newnode will be inserted in such a way that linked list will remain sorted.
      If it gets inserted at the last, then the newnode points to the head.
      If the newnode inserted at the first, then the linked list starts from there.
End
Begin
   function display() to print the list content having n number of nodes:
      Initialize c = 0.
      Initialize pointer variable with the start address
      while (c <= n)
         Print the node info
         Update pointer variable
         Increment c.
End

示例程式碼

#include<iostream>
using namespace std;
struct nod {
   int d;
   nod *n;
}
*p = NULL, *head = NULL, *q = NULL, *np = NULL;
int c = 0;
void createnode(int n) {
   np = new nod;
   np->d = n;
   np->n = NULL;
   if (c == 0) {
      head = np;
      p = head;
      p->n = head;
      c++;
   } else if (c == 1) {
      p = head;
      q = p;
      if (np->d < p->d) {
         np->n = p;
         head = np;
         p->n = np;
      } else if (np->d > p->d) {
         p->n = np;
         np->n = head;
      }
      c++;
   } else {
      p = head;
      q = p;
      if (np->d < p->d) {
         np->n = p;
         head = np;
         do {
            p = p->n;
         }
         while (p->n != q);
         p->n = head;
      } else if (np->d > p->d) {
         while (p->n != head && q->d < np->d) {
            q = p;
            p = p->n;
            if (p->n == head) {
               p->n = np;
               np->n = head;
            } else if (np->d< p->d) {
               q->n = np;
               np->n = p;
               break;
            }
         }
      }
   }
}
void display(int i) {
   nod *t = head;
   int c = 0;
   while (c <= i ) {
      cout<<t->d<<"\t";
      t = t->n;
      c++;
   }
}
int main() {
   int i = 0, n, a;
   cout<<"enter the no of nodes\n";
   cin>>n;
   while (i < n) {
      cout<<"\nenter value of node\n";
      cin>>a;
      createnode(a);
      i++;
   }
   cout<<"sorted circularly singly link list"<<endl;
   display(n);
}

輸出

enter the no of nodes
5
enter value of node
6
enter value of node
4
enter value of node
7
enter value of node
3
enter value of node
2
sorted circularly singly link list
2 3 4 6 7 2

更新日期: 2019-7-30

438 次瀏覽

開啟你的 職業

完成課程,獲得認證

開始
廣告