单向链表复习:
2020/10/24
(1)创建链表
typedef struct node
{
int data;
struct node* next;
} node;
node* createList()
{
//创建链表
node* Headnode = (node*)malloc(sizeof(node));
Headnode->next = NULL;
return (Headnode);
}
(2)创建节点
node* createNode(int data)
{
//创建节点
node* newnode = (node*)malloc(sizeof(node));
newnode->data = data;
newnode->next = NULL;
return (newnode);
}
(3)插入节点
//头插法插入节点
void insertNode(node* Head,int data)
{
node* insertNode = createNode(data);
insertNode->next=Head->next;
Head->next = insertNode;
}
//尾插法插入节点
node* add(int n, node * head)
{
node * t = createNode(n);
t->next = NULL;
if (head == NULL)
{
head = t;
}
else if (head->next == NULL)
{
head->next = t;
}
else{
node * p = head->next;
while (p->next != NULL)
{
p = p->next;
}
p->next = t;
}
return head;
}
(4)删除节点
//删除节点
void deleteNodebydata(node* Head,int data)
{
node* MoveNode = Head->next;
node* Frontnode = Head;
if(MoveNode == NULL)
{
printf("List is empty!\n");
}
else
{
while(MoveNode->data!=data)
{
Frontnode = MoveNode;
MoveNode = MoveNode->next;
if(MoveNode == NULL)
{
printf("Cant find that num.\n");
break;
}
}
Frontnode->next = MoveNode->next;
free(MoveNode);
}
}
(5)打印链表
//顺序打印链表
void PrintList(node* Head)
{
if(Head == NULL) return;
node* pMove = Head->next;
while(pMove)
{
printf("%d\t",pMove->data);
pMove = pMove->next;
}
printf("\n打印完成\n");
}
//逆序打印(只写了递归实现)
//常用方法有递归,栈,逆序
void rprint(node *head)
{
if(head == NULL)
{
return;
}
else
{
rprint(head->next);
printf("%d\t",head->data);
}
}
快速复习使用,变量或者节点命名很不严谨,影响阅读请见谅。