简体   繁体   English

如何使链表在 C++ 中有序?

[英]How to make the linked list ordered in C++?

#include <iostream>
#include <string>
using namespace std;
struct node
{
    int num;
    node*next;
};

bool isEmpty(node *head);
char menu();
void insertasfirstelement(node *&head, node *&last, int num);
void insert(node *&head, node *&last, int num);
void remove(node *&head, node *&last);
void showlist(node*c);

bool isEmpty(node*head)
{
    if(head == NULL)
        return true;
    else
        return false;
}
char menu()
{
    char choice;

    cout << "\n\nMenu:\n";
    cout << "\n1. Add an item";
    cout << "\n2. Remove an item";
    cout << "\n3. Show the list";
    cout << "\n4. Exit" <<endl;

    cin >> choice;
    return choice;
}
void insertasfirstelement(node *&head, node*&last, int num)
{
    node * temp = new node;
    temp ->num=num;
    temp ->next=NULL;
    head = temp;
    last = temp;
}
void insert(node *&head, node *&last, int num)
{
    if(isEmpty(head))
        insertasfirstelement(head,last,num);
    else
    {
        node *temp = new node;
        temp ->num=num;
        temp ->next=NULL;
        last ->next= temp;
        last = temp;
    }
}
void remove(node *&head, node *&last)
{
    if(isEmpty(head))
        cout << "List is empty\n";
    else if(head ==  last)
    {
        delete head;
        head = NULL;
        last = NULL;
    }
    else
    {
        node *temp = head;
        head = head -> next;
        delete temp;

    }
}
void showlist(node*c)
{
    if(isEmpty(c))
        cout <<"The list is empty\n";
    else
    {
        cout << "The values are: \n";
        while(c !=NULL)
        {
            cout << c -> num << endl;
            c = c -> next;
        }
    }
}
int main()
{
    node *head=NULL;
    node *last=NULL;
    char choice;
    int num;

    do{
        choice = menu();

        switch(choice)
        {
            case '1':   cout << "Please enter a number: ";
                        cin >> num;
                        insert(head, last, num);
                        break;
            case '2':   remove(head,last);
                        break;
            case '3':   showlist(head);``
                        break;
            default:    cout << "System exit\n";
        }
    } while(choice != '4');
}

So I have been able to get a working linked list going.所以我已经能够得到一个有效的链表。 But I haven't been able to figure out how to get it in order.但我一直无法弄清楚如何按顺序排列。 I also don't know how to make it so I can delete a number that I have inserted.我也不知道如何制作它,所以我可以删除我插入的数字。 I'm trying to understand how linked lists work better so if you can provide some help it would be greatly appreciated.我试图了解链接列表如何更好地工作,因此如果您能提供一些帮助,将不胜感激。

You can make linked list ordered by comparing the data field of the node您可以通过比较节点的数据字段来使链表有序

Try this way :试试这个方法:

1 - Till the node is NULL travel through linked list. 1 - 直到节点为 NULL 遍历链表。

2 - If data of the current node is less than the data of the next node then swap the both data. 2 - 如果当前节点的数据小于下一个节点的数据,则交换两者的数据。

3 - else move to the next node 3 - 否则移动到下一个节点

And if you want to order linked list without swapping data ... ie changing the next of node then you can also do that way..如果您想在不交换数据的情况下订购链表......即更改节点的下一个,那么您也可以这样做..

For deleting the node用于删除节点

try this way试试这个方法

1- Ask user to enter data of the node which he/she wants to delete. 1- 要求用户输入他/她要删除的节点的数据。

2- search for that node which has that data. 2-搜索具有该数据的节点。

3- if that node is found delete that node. 3- 如果找到该节点,则删除该节点。

4- else find node in remaining linked list. 4- 否则在剩余链表中查找节点。

Note : This is just like how to do... you have to build the logic so that you can maintain consistency in the linked list :)注意:这就像如何做...您必须构建逻辑,以便您可以在链表中保持一致性:)

Both of the following functions assume you want a linked list sorted in ascending order.以下两个函数都假设您想要一个按升序排序的链表。

To insert a new node into your linked list object, you could try:要将新节点插入到链表对象中,您可以尝试:

void insert(node *&head, node *&last, int num)
{
    if(isEmpty(head))         
        insertasfirstelement(head,last,num);
    else if(num > tail->num)    //if new number to be inserted is greater than tail, insert at end and avoid needless iteration through list
    {
        node* temp = new node;
        temp->num = num;
        temp-next = NULL;
        last->next = temp;
        last = temp;
    }
    else
    {
        node *temp = new node;
        temp ->num=num;
        temp ->next=NULL;
        node* ptr = head;    //to lead iteration through linked list
        node* prev = NULL;  //to trail ptr
        while(ptr && (ptr->num > temp->num))  //iterate through linked list while new node's value is less than ptr's value and ptr is not beyond end of list (assuming last->next == NULL)
        {
            prev = ptr;
            ptr = ptr->next;
        }
        if(!prev)            // if prev never iterated, the temp node is the new head node
       {
           head = temp;
           head->next = ptr;
       }
       else if(prev == last)  //if prev is tail, the temp node is the new tail node
       {
           prev->next = temp;
           tail = temp;
       }
       else   //otherwise, insert temp node in between prev and ptr
       {
            prev-next = temp;
            temp->next = ptr;
       }
    }
}

To delete a node from your linked list object try:要从链表对象中删除节点,请尝试:

void remove(node *&head, node *&last, int x) // added a int parameter to determine which node is to be removed
{
    if(isEmpty(head))
        cout << "List is empty\n";
    else 
    {
        node* ptr = head;
        node* prev = NULL;
        while(ptr && (ptr->num != x)   //iterate through linked list while desired value to be deleted is not found and have not gone through entire list
        {
            prev = ptr;
            prt = ptr->next;
        } 
        if(!prev)      //if prev never iterated, the head is the value to be deleted
        {
            node* garbage = head;
            head = head->next;
            delete garbage;
        }
        else if(ptr==tail)   //if the value to be deleted is the tail's value, reassign tail to prev and delete ptr
        {
           tail = prev;
           tail->next = NULL;
           delete ptr;
        }
        else if(!ptr)   //if ptr == NULL, value to be deleted was not in list
        {
            cout << "Value " << x << " could not be found in list.\n";     // or throw exception 
        }
        else      //reassign prev's next to ptr's next and delete ptr;
        {
            prev-next = ptr->next;
            delete ptr;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM