#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
class Node
{
public:
int data;
Node* next;
Node(int a)
{
data=a;
}
Node()
{
data=0;
}
};
class List{
public:
int data;
Node* m_plist;
int m_iLength;
List()
{
m_plist = new Node;
m_plist->next= NULL;
m_plist->data=0;
m_iLength = 0;
}
void list_clear()
{
Node* temp = m_plist->next;
while(temp!=NULL)
{
Node* linshi = temp->next;
delete temp;
temp = linshi;
}
m_plist->next = NULL;
}
~List()
{
list_clear();
delete m_plist;
}
bool list_empty()
{
if(m_iLength==0)
return true;
else
return false;
}
int list_length()
{
return m_iLength;
}
bool list_inserthead(Node* a)
{
Node* temp = m_plist->next;
Node* newnode = new Node;
if(newnode==NULL)
return false;
newnode->data = a->data;
m_plist->next=newnode;
newnode->next = temp;
m_iLength++;
return true;
}
bool list_insertail(Node* a)
{
Node* currentNode = m_plist;
while(currentNode->next!=NULL)
{
currentNode=currentNode->next;
}
Node* temp = new Node;
if(temp==NULL)
return false;
temp->data = a->data;
temp->next=NULL;
currentNode->next=temp;
m_iLength++;
return true;
}
bool list_insert(int i,Node* a)
{
if(i<0||i>m_iLength)
return false;
Node* currentNode = m_plist;
for(int k=0;k<i;k++)
{
currentNode = currentNode->next;
}
Node* temp = new Node;
if(temp==NULL)
return false;
temp->data = a->data;
temp->next = currentNode->next;
currentNode->next = temp;
m_iLength++;
return true;
}
bool list_delete(int i,Node* a)
{
if(i<0||i>=m_iLength)
{
return false;
}
Node* currentNode = m_plist;
Node* currentNodeBefore = NULL;
for(int k=0;k<=i;k++)
{
currentNodeBefore = currentNode;
currentNode = currentNode->next;
}
currentNodeBefore->next = currentNode->next;
a->data = currentNode->data;
delete currentNode;
currentNode = NULL;
m_iLength--;
return true;
}
bool list_getelem(int i,Node* p)
{
if(i<0||i>=m_iLength)
{
return false;
}
Node* currentNode = m_plist;
Node* currentNodeBefore = NULL;
for(int k=0;k<=i;k++)
{
currentNodeBefore = currentNode;
currentNode = currentNode->next;
}
p->data = currentNode->data;
return true;
}
int list_locatelem(Node* a)
{
Node* currentNode = m_plist;
int i=0;
while(currentNode->next!=NULL)
{
currentNode=currentNode->next;
if(currentNode->data==a->data)
{
return i;
}
i++;
}
return -1;
}
void see()
{
Node* temp=m_plist;
while(temp->next!=NULL)
{
temp=temp->next;
cout<<temp->data<<endl;
}
}
};
int main()
{
Node node1(10);
Node node2(11);
Node node3(12);
Node node4(13);
Node node5(14);
List* plist = new List;
plist->list_inserthead(&node1);
plist->list_insertail(&node2);
plist->list_insertail(&node3);
plist->list_insertail(&node5);
// cout<<plist->list_length()<<endl;
plist->list_insert(3,&node4);
plist->see();
cout<<"-------------------------"<<endl;
system("pause");
Node node6;
plist->list_getelem(0,&node6);
cout<<node6.data<<endl;
system("pause");
cout<<plist->list_locatelem(&node3)<<endl;
delete plist;
plist = NULL;
}
链表操作实现
最新推荐文章于 2021-11-30 00:36:33 发布