首页 > 其他 > 详细

数据结构-线性表-链表实现

时间:2021-04-25 23:18:17      阅读:21      评论:0      收藏:0      [点我收藏+]

任务

有一链表里面存放的是某公司产品名称及销量,目前链表中的数据是按产品销量从小到大排序的,请编写一个算法,利用原链表空间,将链表中结点变更为按产品销量从大到小排序,并输出销量前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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!