链表是一种重要的数据结构,本文实现了链表的创建,插入,删除,获取链表大小,链表的反转等操作。
博主最近学习很忙,就简单的贴下代码。
#include <iostream>
using namespace std;
struct Node{
int val;
Node* next;
Node(int x):val(x),next(NULL){}
};
class ListNode
{
private:
Node *head;
public:
ListNode(Node *node)
{
head=node;
}
void printlist(Node *head);//打印链表的节点值
int getsize(Node *head);//获取链表的大小
void add(int index,int element,Node *&head);//在指定位置插入节点
bool iscontains(int element,Node *head);//判断某个元素是否在链表中
void remove(int index,Node *&head);//删除指定位置的链表
Node* ReverseList(Node *head);//单链表的反转
};
void ListNode::printlist(Node *head)
{
Node *temp=head;
while(temp!=NULL)
{
cout<<temp->val<<"\t";
temp=temp->next;
}
cout<<endl;
}
int ListNode::getsize(Node *head) {
int size=0;
Node *temp=head;
while(temp!=NULL)
{
size++;
temp=temp->next;
}
return size;
}
void ListNode::add(int index, int element, Node *&head) //在指定位置插入节点
{
Node *node=new Node(element);
Node *temp=head;//指向头结点
int size=getsize(head);
if (index<0||index>=size)
{
cout<<"out of range!"<<endl;
return;
}
if (index==0)
{
node->next=temp;
head=node;
return ;
}
for(int i=1;i<index;i++)
{
temp=temp->next;
}
node->next=temp->next;
temp->next=node;
}
bool ListNode::iscontains(int element, Node *head)
{
Node *temp=head;
while(temp!=NULL)
{
if(temp->val==element)
return true;
temp=temp->next;
}
return false;
}
void ListNode::remove(int index, Node *&head)
{
int size=getsize(head);
Node *temp=head;
if(index>=size||index<0)
{
cout<<"out of range!"<<endl;
return;
}
if(index==0)
{
head=head->next;
return;
}
for(int i=1;i<index;i++){
temp=temp->next;
}
temp->next=temp->next->next;
}
Node* ListNode::ReverseList(Node *head)
{
if(head==NULL){
return head;
}
Node *curNode=head,*nextNode=head->next,*temp;
while(nextNode!= nullptr)
{
temp=nextNode->next;
nextNode->next=curNode;
curNode=nextNode;
nextNode=temp;
}
head->next=NULL;
head=curNode;
return head;
}
int main()
{
int a[6]={1,3,6,8,9,10};
Node *head=new Node(1);//新建头结点
ListNode list=ListNode(head);
Node *temp=head;
// list.printlist(head);
for(int i=1;i<6;i++)
{
temp->next=new Node(a[i]);
temp=temp->next;
}
cout<<"the original LinkList is :"<<endl;
list.printlist(head);
cout<<list.getsize(head)<<endl;
list.add(3,-9,head);
list.printlist(head);
cout<<list.getsize(head)<<endl;
cout<<list.iscontains(8,head)<<endl;
list.remove(0,head);
list.printlist(head);
Node *rehead;
rehead=list.ReverseList(head);
list.printlist(rehead);
}
运行结果: