创建一个名为 LinkedList 的类,实现链表的基本操作,包括插入节点、删除节点和反转链表等
#include<iostream>
using namespace std;
class LinkedNode{
public:
int x;
LinkedNode *next;
LinkedNode(){
x = 0;
next = NULL;
}
LinkedNode(int x)
{
this->x = x;
next = NULL;
}
};
class LinkedList{
private:
LinkedNode *head;
public:
LinkedList()
{
head == NULL;
}
//链表的尾插法
LinkedNode *ins(LinkedNode *p)
{
if(NULL == head)
{
this->head = p;
return head;
}
LinkedNode *q = head;
while (q->next != NULL)
{
q = q->next;
}
q->next = p;
return head;
}
//输出
void show(LinkedNode *head)
{
LinkedNode *pi = head;
while(pi != NULL)
{
cout << pi->x <<endl;
pi = pi->next;
}
}
//删除链表
LinkedNode *del_list(LinkedNode *head,int x)
{
if(NULL == head)
{
cout <<"没有数据,无法删除" <<endl;
}
if(head->x == x)
{
head->next = head;
}
LinkedNode *pi = head;
if(pi->next != NULL &&pi->next->x != x)
{
pi = pi->next;
}
else
{
LinkedNode *pn = pi->next;
pi->next = pn->next;
}
return head;
}
//反转链表
LinkedNode *reverse(LinkedNode *head)
{
if(NULL == head)
{
return NULL;
}
LinkedNode *pi = head->next;
head->next = NULL;
LinkedNode *p = NULL;
while(pi != NULL)
{
p =pi->next;
pi->next = head;
head = pi;
pi = p;
}
return head;
}
};
int main(int argc, char const *argv[])
{
LinkedNode *head = new LinkedNode(1);
LinkedNode *s1 = new LinkedNode(2);
LinkedNode *s2 = new LinkedNode(3);
LinkedNode *s3 = new LinkedNode(4);
LinkedList *s = new LinkedList();
LinkedNode *head_s = s->ins(head);
head_s = s->ins(s1);
head_s = s->ins(s2);
head_s = s->ins(s3);
head_s = s->del_list(head_s,2);
head_s = s->reverse(head_s);
s->show(head_s);
return 0;
}
运行结果