顺序表(C++实现)

实现顺序表的创建、查找、输入、删除等方法


  1 #include <iostream>
  2 using namespace std ;
  3 int Error = 0 ;
  4 
  5 #define MAXLISTLEN 100
  6 int ListLen = 0 ;
  7 int SeqList [MAXLISTLEN + 1] ;
  8 //顺序表查找
  9 int SearchSeqList (int i)
 10 {
 11     if ((i > ListLen) || (i < 1) || (ListLen == 0))
 12     {
 13         Error = -1 ;
 14         return (-1) ;    //查找出错返回
 15     }
 16     else
 17     {
 18         return SeqList [i] ;    //返回指定位置的元素值
 19     }
 20 }
 21 //顺序表的插入
 22 void InsertSeqList (int NewItem , int i)
 23 {
 24     int j ;
 25 
 26     if ((i > ListLen + 1) || (i < 1) || (ListLen == MAXLISTLEN))
 27     {
 28         Error = -2 ;    //插入出错返回
 29         cout << "插入出错啦!!!";
 30     }
 31     else
 32     {
 33         for (j = ListLen ; j >= i ; j -- )    //从后往前移
 34         {
 35             SeqList [j+1] = SeqList [j] ;
 36         }
 37         SeqList [i] = NewItem ;        //插入新元素
 38         ListLen = ListLen + 1 ;        //表长加一
 39     }
 40 }
 41 //顺序表指定位置数据的删除
 42 void DeleteSeqList (int i)
 43 {
 44     int j ;
 45 
 46     if ((i > ListLen)||(i < 1) || (ListLen == 0))
 47     {
 48         Error = -3 ;    //删除出错返回
 49         cout << "删除出错啦!!!" ;
 50     }
 51     else
 52     {
 53         for (j = i ; j < ListLen ; j ++ )    //从前往后移
 54         {
 55             SeqList [j] = SeqList [j+1] ;
 56         }
 57         ListLen = ListLen - 1 ;        //表长减一
 58     }
 59 }
 60 //顺序表显示
 61 void ShowSeqList ()
 62 {
 63     int i ;
 64 
 65     cout << "The list : " ;
 66     for (i = 1 ; i <= ListLen ; i ++ )
 67     {
 68         cout <<SeqList[i]<<" " ;    //逐个显示数据元素
 69     }
 70     cout << endl ;            //换行
 71 
 72 }
 73 //主函数
 74 int main (int argc , char * argv[])
 75 {
 76 int r[MAXLISTLEN] , i , SearchPos , NewPos , NewItem , DelPos ;
 77 
 78 cout << "Please input the ListLen : " ;
 79 cin >> ListLen ;    //输入样本数目(表长)
 80 //创建顺序表
 81 for (i = 1 ; i <= ListLen ; i++)
 82 {
 83     cout << "Please input No." << i <<"Item : " ;
 84     cin >> SeqList[i] ;
 85 }
 86 ShowSeqList () ;    //显示顺序表
 87 
 88 cout << "Please input the search pos : " ;
 89 cin >> SearchPos ;    //输入查找位置
 90 
 91 cout << "Your Searched Item is : " <<SearchSeqList (SearchPos) << endl ;    //输出查找的数据元素值
 92 
 93 cout << "Please input the NewPos where you want to insert : " ;
 94 cin >> NewPos ;        //插入位置输入
 95 cout << "Please input the NewItem what you want to insert : " ;
 96 cin >> NewItem ;    //插入元素输入
 97 InsertSeqList (NewItem , NewPos) ;    //新数据插入顺序表中
 98 cout << "After insert : " ;
 99 ShowSeqList () ;        //插入数据后,输出新的顺序表
100 
101 cout << "Please input the DelPos where you want to delete : " ;
102 cin >> DelPos ;        //输入删除元素位置
103 DeleteSeqList (DelPos) ;    //按位置删除数据
104 cout << "After delete : " ;
105 ShowSeqList () ;
106 
107 if (Error < 0) cout <<"Error" << Error << endl ;
108 
109 return 0 ;
110 }

 

posted @ 2016-10-09 17:40  maoguy  阅读(12661)  评论(2编辑  收藏  举报