简体   繁体   English

如何插入已排序的单链表?

[英]How to insert into a sorted singly linked list?

I am making a sorted linked list where the user enters a number and the number is inserted into sorted position. 我正在制作一个有序链表,用户输入一个数字,然后将数字插入到排序位置。 I am currently having problems with the sort function. 我目前在排序功能方面遇到问题。

  class Node
    {
    public:
        int data;
        class Node *next;

        Node(int info, Node *ptr = 0) 
        {
            data = info; 
            next = ptr;
        }
    };
    class Node *head = NULL;


    class stack
    {
    private:
        Node *temp;
    public: 
        stack()
        {
            temp = 0;
        }
        bool isEmpty()
        {
        return temp == NULL;
    }

I decided to go with an insert function(its called sort but really it just inserts a node into the linked list) which is why i have a current pointer and a previous pointer. 我决定使用插入函数(它被称为sort,但实际上它只是将一个节点插入到链表中),这就是为什么我有一个当前指针和一个前一个指针。 I guess my question is am i on the right path? 我想我的问题是我在正确的道路上吗? I am new to this so i just want a little bit of guidance to figure this out. 我是新手,所以我只是需要一些指导来解决这个问题。 Any tips will be appreciated. 任何提示将不胜感激。

 void sort(int data)
    {
        class Node *born = new Node(data);
        Node* current = head;
        Node* previous = NULL;
        //the list is empty case
        if (isEmpty())
            temp = born;
        else
        {
            while (current != NULL)
            {
                if (current->data >= temp->data)
                {
                    born->next = current;
                    temp = born;
                    break;
                }
                else
                {
                    previous = current;
                    current = temp->next;
                }
            }
            if (current == head)
            {
                born->next = head;
                head = born;
            }
            else
            {
                born->next = current;
                previous->next = born;
            }

            /*else
            {

                born->next = temp;
                temp = born;
            }*/
        }

    }

    void print()
    {
        cout<<"stack from the top"<<endl;
            for(Node *top = temp; top != 0; top=top->next)
                cout << top->data << " ";
            cout << endl;
        /*while(temp != NULL)
        {

            cout<<temp->data<<" ";
            temp=temp->next;
        }
        */
    }

    int pop()
    {
        if (isEmpty())
                return -999;        

            int intReturn = temp->data;
            Node *top;

            top = temp;

            temp = temp->next;

            delete top;


            return intReturn;

    }

    };
    int main(void)
    {
        int num=0;

        stack boss;
        while(num!=-1)
        {
            cout<<"Please Enter a Number"<<endl;
            cin >> num;
            if (num == -1)
                boss.print();
            else
                boss.sort(num);
        }
        cout<<endl<<endl;


        system("PAUSE");
        return 0;

    }

I have concerns about your code about the logical steps and/or the naming of things. 我对您的代码有关逻辑步骤和/或命名的担忧。 I couldn't just edit your code to fix it, so I've rewritten your code based on this understanding if you agree with me: 我不能只编辑你的代码来修复它,所以如果你同意我,我会根据这种理解重写你的代码:

  • A head points to the first node, and a tail points to the last node. head指向第一个节点, tail指向最后一个节点。
  • Check to see if the list is empty, then head and tail point to the new node. 检查列表是否为空,然后headtail指向新节点。
  • Otherwise, check to see if the new node is to be placed at the start, and do it 否则,请检查是否要将新节点放在开头,然后执行此操作
  • Otherwise, check to see if it fits in the middle, and do it 否则,检查它是否适合中间,然后执行
  • Otherwise, place it at the last place 否则,将它放在最后的位置

In addition, my other changes include: 另外,我的其他变化包括:

A. For the class stack A.对于类stack

  • I renamed it to LinkedList 我将其重命名为LinkedList
  • I put two member variables head and tail to refer to the first and last nodes 我将两个成员变量headtail放在第一个和最后一个节点上

B. For the sort() method B.对于sort()方法

  • I renamed it to insert 我将其重命名为insert
  • I explicitly wrote each of the important cases clearly (empty list, first node, middle node, last node) 我明确地清楚地写了每个重要的情况(空列表,第一个节点,中间节点,最后一个节点)

I also removed the using namespace std and explicitly wrote std:: because it is a better practice. 我还删除了using namespace std并显式编写了std::因为这是一个更好的做法。 There are also some minor changes here and there. 这里和那里也有一些小的变化。

My final code: 我的最终代码:

class Node
{
public:
  int data;
  class Node* next;

  Node(int info, Node* ptr = 0) 
  {
    data = info; 
    next = ptr;
  }
};

class LinkedList
{
private:
  Node* head;
  Node* tail;

public: 

  LinkedList()
  {
    head = 0;
    tail = 0;
  }

  bool isEmpty()
  {
    return head == NULL;
  }

  void insert(int data)
  {
    Node* newNode = new Node(data);

    if (isEmpty())
    {
      head = newNode;
      tail = newNode;
    }
    // if node to be placed at the top
    else if (data > head->data)
    {
      newNode->next = head;
      head = newNode;
    }
    else
    {
      Node* temp = head;
      Node* previousTemp = head;

      while (temp != NULL)
      {
        // if node to be placed in the middle
        if (temp->data < data)
        {
          previousTemp->next = newNode;
          newNode->next = temp;
          break;
        }
        previousTemp = temp;
        temp = temp->next;
      }

      // if node to be placed at the end
      if (temp == NULL)
      {
        tail->next = newNode;
        tail = tail->next;
      }

    }
  }

  void print()
  {
    std::cout << "Stack from the top" << std::endl;
    Node* temp = head;
    while(temp != NULL)
    {
      std::cout << temp->data << " ";
      temp = temp->next;
    }
  }

  int pop()
  {
    if (isEmpty())
    {
      return -999;
    }

    int intReturn = head->data;
    Node *top;

    top = head;

    head = head->next;

     delete top;


     return intReturn;
  }
};

int main(void)
{
  int num = 0;
  LinkedList linkedList;

  while (num != -1)
  {
    std::cout << "Please enter a number: ";
    std::cin >> num;
    if (num == -1)
    {
      linkedList.print();
    }
    else
    {
      linkedList.insert(num);
    }
  }

  std::cout << std::endl << std::endl;

  system("PAUSE");
  return 0;
}

Does this help? 这有帮助吗?

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

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