c++實現單鏈表的各種操作
阿新 • • 發佈:2019-02-12
在下例中,演示了單鏈表的各種操作
執行結果為:#include <iostream> using namespace std; typedef struct Node { int data; //資料域 struct Node * next; //指標域 }NODE, *PNODE; //NODE相當於struct Node, PNODE相當於struct Node * PNODE CreateList(); void TraverseList(PNODE pHead); bool IsEmpty(PNODE pHead); int NodeNumber(PNODE pHead); void SortList(PNODE pHead); bool InsertNode(PNODE pHead, int position, int value); bool DeleteNode(PNODE pHead, int position); int main() { PNODE pHead = NULL; pHead = CreateList(); TraverseList(pHead); if(IsEmpty(pHead)) cout << "連結串列為空" << endl; else cout << "連結串列不為空" << endl; cout << endl; int nodeSum = NodeNumber(pHead); cout << "連結串列有" << nodeSum << "個節點" << endl; cout << "排序後資料分別為:"; SortList(pHead); TraverseList(pHead); cout << "插入資料後,資料分別為:"; InsertNode(pHead, 3, 22); TraverseList(pHead); cout << "刪除資料後,資料分別為:"; DeleteNode(pHead, 2); TraverseList(pHead); return 0; } PNODE CreateList() //建立一個單鏈表 { int nodeNumber; int val; //存放輸入的每個節點的值 PNODE pHead = new NODE; PNODE pTail = pHead; pTail->next = NULL; cout << "Enter the number of nodes you want to create: "; cin >> nodeNumber; if(pHead == NULL) { cout << "分配失敗,程式終止." << endl; } for(int i=0; i<nodeNumber; i++) { cout << "The " << i+1 << "th node is "; cin >> val; PNODE pNew = new NODE; if(pNew == NULL) { cout << "分配失敗,程式終止." << endl; } pNew->data = val; pTail->next = pNew; pNew->next = NULL; pTail = pNew; } return pHead; } void TraverseList(PNODE pHead) //遍歷連結串列 { PNODE p = pHead->next; cout << "資料分別為:"; while(p != NULL) { cout << p->data << " "; p = p->next; } cout << endl; } bool IsEmpty(PNODE pHead) //判斷連結串列是否為空 { if(pHead->next == NULL) return true; else return false; } int NodeNumber(PNODE pHead) //獲取節點個數 { PNODE p = pHead->next; int nodeSum = 0; while(p != NULL) { nodeSum++; p = p->next; } return nodeSum; } void SortList(PNODE pHead) //排序 { int i, j, t; PNODE p, q; int length = NodeNumber(pHead); for (i=0, p=pHead->next; i<length - 1; i++, p=p->next) { for(j=i+1, q=p->next; j<length; j++, q=q->next) { if(p->data > q->data) { t = p->data; p->data = q->data; q->data = t; } } } } bool InsertNode(PNODE pHead, int position, int value) //插入節點 { int i = 0; PNODE p = pHead; PNODE pNew = new NODE; int length = NodeNumber(pHead); //獲取連結串列的節點個數 if(position>0 && position<=length) { while(i<position) { p = p->next; i++; } pNew->data = value; PNODE q = p->next; p->next = pNew; pNew->next = q; return true; } else return false; } bool DeleteNode(PNODE pHead, int position) //刪除節點 { int i = 0; PNODE p = pHead; int length = NodeNumber(pHead); if(position>0 && position<=length) { while(i < position-1) { p = p->next; i++; } PNODE q = p->next->next; delete p->next; p->next = q; p->next = q; return true; } else return false; }