算法与数据结构——表
单链表
参考了《数据结构与算法分析》的表。
力扣学习
单链表的基础功能
#include<iostream>
using namespace std;
//单向链表(带头节点)
typedef struct node* PtrToNode;
typedef PtrToNode List;
typedef PtrToNode Position;
struct node
{
int data;
Position Next;
};
bool IsEmpty(List L)
{
if (L->Next == NULL)
return true;
else
return false;
}
bool IsLast(Position P, List L)
{
if (P->Next == NULL)
return true;
else
return false;
}
Position Find(int data, List L)
{
Position P;
P = L->Next;
while (P != NULL && P->data != data)
P = P->Next;
return P;
}
Position FindPrevious(int data, List L)
{
Position P;
P = L;
while (P->Next != NULL && P->Next->data != data)
{
P = P->Next;
}
return P;
}
void Delete(int data, List L)
{
Position P, TmpCell;
P = FindPrevious(data, L);
if (!IsLast(P, L))
{
TmpCell = P->Next;
P->Next = TmpCell->Next;
free(TmpCell);
}
}
void Insert(int data, List L,Position P)
{
//在P节点后插入
Position TmpCell;
TmpCell = new node;
TmpCell->data = data;
TmpCell->Next = P->Next;
P->Next = TmpCell;
}
void DeleteList(List L)
{
Position P, Tmp;
P = L->Next;
L->Next = NULL;
while (P != NULL)
{
Tmp = P->Next;
free(P);
P = Tmp;
}
}
逆置链表
参考博客,有图解更好理解
List Reverse( List L )
{
Position Old_head, New_head, Temp;
New_head = NULL;
Old_head = L->Next;
while ( Old_head ) {
Temp = Old_head->Next;
Old_head->next=New_head;
New_head = Old_head;
Old_head = Temp;
}
L_Next=New_head;
return L;
}