1. 程式人生 > >C++ linked list 中新增某一個特定位置節點

C++ linked list 中新增某一個特定位置節點

下面在NewContactList中新增一個插入節點的operations。

NOTE: 用code::blocks 編寫的程式, 360報木馬, 拒接編譯:

查找了一下原因, 說是和code:blocks 無關, 而是和GCC 的編譯器有關(我設定的預設的GCC 的編譯器)。解決辦法是, 開啟360衛士, 木馬查殺欄目下面的恢復區, 恢復專案。  雖然執行完之後又會報告木馬。

下面值給出NewContactList工程做了改動的的幾個程式(檢視完整程式的所有相關檔案, 參考前面blog內容):

/*
 *ContactList.h
 *
 *   created on Jul 6, 2014
 *      Author: ***
 *
 *
 */

 #ifndef CONTACT_LIST_H
 #define CONTACT_LIST_H


 #include "Contact.h" // the first thing to do is to include the node header file

 class ContactList {
     public:
        ContactList(); // prototype for constructor
        void AddToHead(const std::string&);//reference, 避免複製, 更快, const, 所以不讓修改
         void printList();
        void insert(const std::string& inputName); // 新新增的

     private:
        Contact* head;
        int length;
};

 #endif /*end of CONTACT_LIST_H*/

ContactList.cpp 如下:

// an implementation of ContactList.h

#include "ContactList.h"
using namespace std;

ContactList::ContactList():head(0), length(0) {

}

void ContactList::AddToHead(const string& name) {
   Contact* newOne = new Contact(name);
   if(head == 0) {
      head = newOne;
   }
   else {
      newOne -> next = head;
      head = newOne;
   }
   length++;
}

void ContactList::printList() {
   Contact* tp;

   tp = head;

   while(tp != NULL) {
      cout << tp -> name << endl;

      tp = tp -> next;
   }
}

void ContactList::insert(const string& inputName) {
   Contact* newNode = new Contact(inputName);//create a node in the heap
   //case1 - empty list
   if(head == 0) {
      head = newNode;
   }
   else {

   Contact* curr = head;
   Contact* trail = 0;
   //Traverse the list to find insert location
   while(curr != 0) {
      if(curr -> name >= newNode ->name) {
         break;
      }
      else {
         trail = curr;
         curr = curr -> next;
      }
   }
   //case2 - insert at head(not empty)
   if(curr == head) {
      newNode -> next = head;
      head = newNode;
   }
   else {

   //case3 - insert somewhere after the head(not empty)
      newNode -> next = curr;
      trail -> next = newNode;
   }
   }
   length++; // incrementing the size
}


測試應用程式NewContactListApp.cpp如下:

#include "ContactList.h"
using namespace std;

int main() {
   ContactList* cl1 = new ContactList;
   string name;
   while(true) {
      cout << "Enter the name of the contact, or q to quit:";
      cin >> name;
      if(name == "q")
         break;
      cl1->insert(name); // so that we can have a sorted linked list
   }

   cl1 -> printList();
   return 0;
}

執行結果如下: