在下例中,演示了链表的各种操作
#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; }
运行结果为:
链表
时间: 2024-11-04 17:11:00