有一链表里面存放的是某公司产品名称及销量,目前链表中的数据是按产品销量从小到大排序的,请编写一个算法,利用原链表空间,将链表中结点变更为按产品销量从大到小排序,并输出销量前3的产品及销量。(测试数据自行设计)
结点类型定义如下:
typedef struct node
{
char productName[20]; //产品名
int saleAmount ;//销量
struct node *next;//指向下一产品的指针
}NODE ;
typedef struct node *pNode ;
#include <iostream>
#include <cstring>
using namespace std;
typedef int DataType ;
struct node{
char productName[20];
DataType saleAmount;
struct node *next;
}NODE;
typedef struct node * pNode ;
// 创建空线性表
pNode createNullList(){
pNode head = new struct node;
if(head == NULL) return NULL;
head->saleAmount = 0;
head->next = NULL;
return head;
}
// 尾部插入
void insertTail(pNode llist, DataType x, char name[20]){
pNode temp, tail;
temp = new struct node;
strcpy(temp->productName, name);
temp->saleAmount = x;
temp->next = NULL;
tail = llist->next;
if(tail==NULL){
llist->next = temp;
return;
}
while(tail->next != NULL) tail = tail->next;
tail->next = temp;
}
// 头部插入
void insertHead(pNode llist, DataType x, char name[20]){
pNode temp;
temp = new struct node;
strcpy(temp->productName, name);
temp->saleAmount = x;
temp->next = llist->next;
llist->next = temp;
}
// 输出线性表
void printList(pNode head){
pNode cur;
cur = head->next;
while(cur!=NULL){
cout<<"name: "<<cur->productName<<" 价格: "<<cur->saleAmount<<endl;
cur = cur->next;
}
}
// 反转
pNode reverse(pNode head){
pNode cur, other;
cur = head;
other = head->next;
cur->next = NULL;
while(other != NULL){
insertHead(cur, other->saleAmount, other->productName);
other = other->next;
}
return cur;
}
int main(){
char name[20];
int saleAmount = 0, max=10;
pNode head, cur;
head = createNullList();
for(int i=0; i<max; i++){
name[0] = (char)(i+‘a‘);
insertTail(head, i, name);
}
printList(head);
cout<<"反转后最大3个: "<<endl;
reverse(head);
cur = head->next;
for(int i=0; i<3; i++){
cout<<"name: "<<cur->productName<<" 价格: "<<cur->saleAmount<<endl;
cur = cur->next;
}
return 0;
}
原文:https://www.cnblogs.com/ag-chen/p/14701508.html