创建带有头结点的链表,在删除和插入操作中会使算法更加简单高效。
#include<iostream>
using namespace std;
struct node {
int data;
node* next;
};
//循环创建带有表头的链表:
node* create(int n) {
node* head, * tail, * p;
head = tail = new node;
head->data = 0;
while (n--) {
p = new node;
cin >> p->data;
p->next = NULL;
tail->next = p;
tail = p;
}
return head;
}
//删除链表中的最小元素。
void deleteMin(node* head) {
//head带有表头节点
node* p = head->next, * q = head;
node* minp = head->next,* minq = head;
while (p) {
if (p->data < q ->data)minp = p, minq = q;
p = p->next;
q = q -> next;
}
minq->next = minp->next;//如果没有头结点当链表第一个元素恰好是最小值时会出现错误。
delete minp;
}
int main() {
int n = 3;
node* p;
p = create(3);
deleteMin(p);
p = p->next;//跳过表头指针
while (p) {
cout << p->data << " ";
p = p->next;
}
return 0;
}