【问题标题】:Using Insertion Sort in a single linked list and deleting nodes在单个链表中使用插入排序并删除节点
【发布时间】:2016-09-15 08:28:44
【问题描述】:

我正在尝试编写一个代码,其中给出了 10 个数字(未排序),我必须使用插入排序对它们进行排序并删除节点。例如,如果这 10 个数字是

50 20 30 10 100 90 80 70 60 40

结果应该是

10 20 30 40 50 60 70 80 90 100
50 被删除
10 20 30 40 60 70 80 90 100
20 被删除
10 30 40 60 70 80 90 100
30被删除
...
40

因此,节点按照最初给出的顺序被删除。 void PrintNode(), callInsertNode(),callDeleteNode() 是顺便给的(其他的这里就不贴了,我只贴了必要的),我尝试完成了void InsertNode(int v) 和void DeleteNode (诠释五)。

 class Node{
    public:
       int value;
       Node *next;
}; 
class LinkedList{ //Singly Linked List
    public:
        LinkedList(){
        head=NULL;
    private:
        Node *head;
        int *x;
        int n;
 }
 void InsertNode(int v){
    cout<<v<<" is inserted"<<endl;

    Node* cur=head;
    if(cur== NULL || cur->next == NULL) {
       return;
    }

    Node *t1 = cur->next;
    while(t1 != NULL) {
        int sec_data = t1->value;
        int found = 0;
        Node *t2 = cur;
        while(t2 != t1) {
            if(t2->value > t1->value && found == 0) {
                sec_data = t2->value;
                t2->value = t1->value;
                found = 1;
                t2 = t2->next;
            } else {
                if(found == 1) {
                    int temp = sec_data;
                    sec_data = t2->value;
                    t2->value= temp;
              }
                t2 = t2->next;
          }
       }
       t2->value = sec_data;
       t1 = t1->next;
 }     

   void PrintNode(){
      Node *cur=head; 
      while(cur!=0){
          cout<<cur->value<<" "; 
          cur=cur->next; 
      } 
      cout<<endl;
   }
   void CallInsertNode(){
      int i;
      for(i=0; i<n; i++)      
         InsertNode(x[i]);   
   }

   void CallDeleteNode(){
      int i;
      for(i=0; i<n; i++){  
          DeleteNode(x[i]); 
          this->PrintNode(); 
      }
   }
   void DeleteNode(int v){
      cout<<v<<" is deleted."<<endl;

      Node *cur=head;
      Node *previous = head; 
      Node *delNode=cur;

      while(cur!=NULL) 
          if(cur->value == v)
         {
           previous->next = delNode->next; 
           delete delNode;
           return;
         }
         previous = cur; 
         cur=cur->next;
     }

【问题讨论】:

  • 问题是什么?
  • 我想知道我写的代码对不对!

标签: sorting nodes singly-linked-list insertion-sort


【解决方案1】:

是的,在我看来是正确的。只需对一些随机数据进行一些测试,以防我遗漏/忽略某些东西。但除此之外(通过代码并空运行)它看起来还可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多