64,646
社区成员
发帖
与我相关
我的任务
分享
#include <iostream>
using namespace std;
class ListNode
{
public:
int key;
ListNode *next;
ListNode():next(NULL){}
ListNode(int x):key(x),next(NULL){}
~ListNode(){};
};
class LinearList
{
private:
int size;
ListNode *head;
public:
LinearList(void) ;
~LinearList(void);
bool insert(int x, int pos);
bool remove(int &x, int pos);
int element(int pos) const;
int search(int x) const;
int length() const;
ListNode* find(int i)const;
};
LinearList::LinearList(void)
{
size = 0;
head = new ListNode();
head->next = NULL;
}
ListNode* LinearList::find(int i)const
{
ListNode *node = head;
int x = 0;
while ((x++ <i)&&(node!=NULL))
node = node->next;
return node;
}
bool LinearList::insert(int x, int pos)
{
if (x <0 || x>size)
{
std::cout <<"ArrayOutOfBound!";
return false;
}
ListNode *node = new ListNode(x);
ListNode *cur = find(pos);
node->next = cur->next;
cur->next = node;
size++;
return true;
}
bool LinearList::remove(int &x, int pos)
{
if (x <=0 || x>size)
{
std::cout <<"ArrayOutOfBound!";
return false;
}
ListNode *pre = find(pos-1);
ListNode *del = pre->next;
x = del->key;
pre->next = del->next;
delete del;
size--;
return true;
}
int LinearList::element(int pos) const
{
if (pos <=0 || pos>size)
{
std::cout <<"ArrayOutOfBound!";
return 0;
}
ListNode *cur;
cur = find(pos);
return cur->key;
}
//查找值为x的元素,返回元素的位置(第一个元素的位置为1)。未找到时返回0。
int LinearList::search(int x) const
{
int i = 1;
ListNode *itr = head->next;
while (itr!=NULL && itr->key!=x)
{
itr = itr->next;
i++;
}
return i;
}
inline int LinearList::length() const
{
return size;
}
int main(int argc, char **argv)
{
return 0;
}
class ListNode
{
public:
int key;
ListNode *next;
ListNode():next(NULL){}
ListNode(int x):key(x),next(NULL){}
~ListNode(){};//mark
};
class LinearList
{
private:
int size;
ListNode *head;
public:
LinearList(void) ;
~LinearList(void);
bool insert(int x, int pos);
bool remove(int &x, int pos);
int element(int pos) const;
int search(int x) const;
int length() const;
ListNode* find(int i)const; //mark
};
ListNode* LinearList::find(int i) const //mark
{
ListNode *node = head;
int x = 0;
while ((x++ <i)&&(node!=NULL))
node = node->next;
return node;
}