C++ linked list 中添加某一个特定位置节点

来源:互联网 发布:公主联盟静态数据 编辑:程序博客网 时间:2024/04/29 06:08

下面在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;}



 

 

 

 

 

 

 

 

运行结果如下:

0 0
原创粉丝点击