2.链表的插入

insert.h
#include <iostream>
#include <ostream>
using std::ostream;
#define OK 1
#define ERROR 0
class myList
{
public:
   myList(){}
   myList(int v_data)
   {
      data = v_data;
   }
   void setNextValue(myList* nextValue)
   {
      next = nextValue;
   }
   friend ostream& operator <<(ostream &output, myList myList);
   friend bool ListInsert(myList *l, int i, int e);
//member variable
   myList* next;
   int data;
};
insert.cpp

#include "insert.h"
ostream& operator <<(ostream &output, myList myList)
{
   output << myList.data;
   return output;
}
bool ListInsert(myList *L, int i, int e)//insert Node to position of Node 'i'
{
   int j;
   myList* p, *s;
   p = L;
   j = 0;
   while (p && j < i - 1)// seek position of Node 'i'
   {
      p = p->next;
      j++;
   }
   if (!p || j > i)
   {
      return ERROR;
   }
   s = new myList();
   s->data = e;
   if (0 == i - 1)
   {
      s->next = p;
      p = s;
   }
   else
   {
      s->next = p->next;
      p->next = s;
   }
   return OK;
}
main.cpp
#include "insert.h"
int main()
{
   myList l1(1);
   myList l2(2);
   myList l3(3);
   l1.setNextValue(&l2);
   l2.setNextValue(&l3);
   l3.next = nullptr;
   myList* firstPtr = new myList();
   firstPtr = &l1;
   if (ListInsert(firstPtr,1, 4))
   {
      for (int i = 0; i < 4; ++i)
      {
         if (firstPtr != nullptr)
         {
            std::cout << *firstPtr << std::endl;
            firstPtr = firstPtr->next;
         }
         
      }
   }
   else
   {
      std::cout << "Error!";
   }
   
   return 0;
}
CMakeLists
cmake_minimum_required(VERSION 2.8)
project (test1)
aux_source_directory(. DIR_SRC)
add_executable(insert ${DIR_SRC})
install (TARGETS insert DESTINATION ${PROJECT_BINARY_DIR}/install)
#install (FILES "${PROJECT_BINARY_DIR}/*.cpp ${PROJECT_BINARY_DIR}/*.h" DESTINATION ${PROJECT_BINARY_DIR}/build)
set(CMAKE_BUILD_TYPE "Debug")
set(CMAKE_CXX_FLAGS_DEBUG "$ENV{CXXFLAGS} -O0 -Wall -g -ggdb")

猜你喜欢

转载自www.cnblogs.com/aelite/p/9484748.html