#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
//头插动态创建节点
void push(struct Node **head, int num)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node)) ;
node->data = num;
node->next = *head;
(*head) = node;
}
//插入随机节点
void insertafter(struct Node *prevNode, int num)
{
if (prevNode == NULL) return;
struct Node *node = (struct Node *)malloc(sizeof(struct Node)) ;
node->data = num;
node->next = prevNode->next;
prevNode->next = node;
}
//尾插动态
void append(struct Node **head, int num)
{
struct Node *node = (struct Node *)malloc(sizeof(struct Node)) ;
node->data = num;
node->next = NULL;
struct Node *last = *head;
if (*head == NULL) {
*head = node;
return;
}//如果是空链表,创建该节点
while(last->next != NULL) {
last = last->next;
}
last->next = node;
}
//轮询删除指定节点
void deleteNode(struct Node **head, int key)
{
struct Node *tmp, *prev;
tmp = *head;
if (tmp != NULL && tmp->data == key) {
(*head) = tmp->next;
free(tmp);
return;
}
while (tmp != NULL && tmp->data != key) {
prev = tmp;
tmp = tmp->next;
}
if (tmp == NULL) return;
prev->next = tmp->next;
free(tmp);
}
//打印链表
void plist(struct Node *hnode)
{
//指针轮询打印;
while(hnode != NULL) {
printf("%3d ", hnode->data);
hnode = hnode->next;
}
printf("\n");
}
int main()
{
struct Node *head = NULL;
append(&head, 12); // 12->NULL;
push(&head, 26); //26->12->NULL;
insertafter(head, 77); //26->77->12->NULL;FILO;
/* void insertafter(struct Node *prevNode, int num)
{
if (prevNode == NULL) return;
struct Node *node = (struct Node *)malloc(sizeof(struct Node)) ;
node->data = num;
node->next = prevNode->next;
prevNode->next = node;
}*/
insertafter(head->next, 48); //26->77->48->12->NULL;
append(&head,64); //26->77->48->12->64->NULL;
append(&head,35); //26->77->48->12->64->35->NULL;
plist(head);
deleteNode(&head, 26); plist(head); //77->48->12->64->35->NULL
deleteNode(&head,35); plist(head); //77->48->12->64->NULL
deleteNode(&head,12); plist(head); //77->48->64->NULL
deleteNode(&head, 1); plist(head); //77->48->64->NULL
return 0;
}
笔者是学习者,注释可能略拙,如有不足望指针,希望读者通过读以上代码与自己多练习,熟悉对单链表的使用。