1.定义
1.1 单向链表
单向链表只包括:数据域 value 和指针域 *next
A.数据域:用于存储数据的元素值;
B.指针域:用于下一个节点的地址;
struct ListNode
{
int value;
ListNode *next;
}
1.2双向链表
双向链表只包括:数据域 value ,左指针域和右指针域
A.数据域:用于存储数据的元素值;
B.左指针域:用于上一个节点的地址;
C.右指针域:用于下一个节点的地址;
struct ListNode
{
int value;
ListNode *Lnext;
ListNode *Rnext;
}
2.创建,插入,删除,遍历
2.1创建
void CreateList(ListNode* pHead)
{
ListNode* p = pHead; //
for(int i= 0;i<10;i++)
{
ListNode* pNewNode = new ListNode;
pNewNode->value = i;
pNewNode->next = NULL;
p->next = pNewNode;
p = pNewNode;
}
cout<<"创建完成!"<<endl;
}
2.2插入
void InListNode(ListNode *p,int V)
{//插入,需要本节点和值
ListNode *Node = new ListNode;
Node->value = V;
Node->next = p->next;
p->next = Node;
}
2.3删除
已知一个单向链表的表头head,写出一个删除某一个节点的算法,要求先找到此节点,然后删除。
void delListNode(ListNode* head,int key)
{
ListNode *pNode1 = head;
ListNode *pNode2 = NULL;
if(head == NULL)
{
return;
}
else
{
if(pNode1->value == key)
{
head = head->next;
delete pNode1;
}
else
{
while(pNode1 != NULL)
{
pNode2 = pNode1;
pNode2 = pNode1 -> next;
if(pNode2 -> value == key)
{
pNode1 -> next = pNode2 -> next;
delete pNode2;
break;
}
pNode1 = pNode1 -> next;
}
}
}
}
2.4遍历
递归,反向遍历链表;先遍历的节点,后输出;
void LinkedList(ListNode *head)
{//递归,反向遍历链表
if (head!=NULL) {
if (head->next!=NULL) {
LinkedList(head->next);
}
cout <<head->value<<endl;
}
}
3.测试
#include<iostream>
using namespace std;
struct ListNode
{
public:
int value;
ListNode *next;
};
void CreateList(ListNode* pHead)
{
ListNode* p = pHead; //
for(int i= 0;i<10;i++)
{
ListNode* pNewNode = new ListNode;
pNewNode->value = i;
pNewNode->next = NULL;
p->next = pNewNode;
p = pNewNode;
}
cout<<"创建完成!"<<endl;
}
void ListPrint(ListNode* Head)
{
ListNode *p;
p = Head;
while(p != NULL)
{
cout<<"单链表数值:"<<p->value<<endl;
p = p->next;
}
}
void InListNode(ListNode *p,int V)
{//插入,需要本节点和值
ListNode *Node = new ListNode;
Node->value = V;
Node->next = p->next;
p->next = Node;
}
void delListNode(ListNode* head,int key)
{
ListNode *pNode1 = head;
ListNode *pNode2 = NULL;
if(head == NULL)
{
return;
}
else
{
if(pNode1->value == key)
{
head = head->next;
delete pNode1;
}
else
{
while(pNode1 != NULL)
{
pNode2 = pNode1;
pNode2 = pNode1 -> next;
if(pNode2 -> value == key)
{
pNode1 -> next = pNode2 -> next;
delete pNode2;
break;
}
pNode1 = pNode1 -> next;
}
}
}
}
void LinkedList(ListNode *head)
{//递归,反向遍历链表
if (head!=NULL) {
if (head->next!=NULL) {
LinkedList(head->next);
}
cout <<head->value<<endl;
}
}
int main()
{
cout << "***创建单链表***" << endl;
ListNode* head = NULL;
head = new ListNode;
head->value = 0;
head->next = NULL;
CreateList(head);//创建
ListPrint(head);//打印
LinkedList(head);//遍历,先入后出
ListPrint(head);//打印
InListNode(head,15);
ListPrint(head);//打印
delListNode(head,15);
//节点删除
ListPrint(head);//打印
return 0;
}