#include <stdio.h>
#include <malloc.h>
struct node //节点的数据结构
{
int num;
struct node *next;
};
--- --- --- --- --- --- --- 插 入 --- --- --- --- --- --- ---
struct node *insert_node(struct node *head, int n)
{
struct node *p1,*p2,*p3;
p1 = (struct node *)malloc(sizeof(struct node));
(*p1).num = n;
if (head == 0) { head = p1; (*p1).next = 0; } //空链表
else //非空链表
{
p2 = head;
while (n>(*p2).num && (*p2).next!=0)
{ p3 = p2; p2 = (*p2).next; }
if (n > (*p2).num) //插在链表尾(p2后面)
{ (*p2).next = p1; (*p1).next = 0; }
else
{ //插在链表头(p2前面)
if (p2 == head) { head = p1; (*p1).next = p2; }
else //插在链表中(p2和p3之间)
{ (*p3).next = p1; (*p1).next = p2; }
}
}
return head;
}
--- --- --- --- --- --- --- 删 除 --- --- --- --- --- --- ---
struct node *delete_node(struct node *head, int n)
{
struct node *p1,*p2;
if (head==0) printf("/nList is null!/n"); //空链表
else
{
p1 = head;
while((*p1).num!=n && (*p1).next!=0)
{ p2 = p1; p1 = (*p1).next; }
if ((*p1).num == n) //找的到
{
if(p1 == head) head = (*head).next; //要删的是链表
else (*p2).next = (*p1).next; //其他位置
// free(p1) ;
}
else printf("/nNot found!/n"); //找不到
}
return(head);
}
--- --- --- --- --- --- 链 表 反 转 --- --- --- --- --- ---
struct node *inverse(struct node *head)
{
struct node *p1,*p2,*p3;
p1 = (*head).next; p2 = head; (*p2).next = 0; p3 = p2;
while(p1)
{ p2 = p1; p1 = (*p1).next; (*p2).next = p3; p3 = p2; }
head = p2; return head;
}
--- --- --- --- --- --- --- 调 用 --- --- --- --- --- --- ---
void main()
{
struct node a,b,c,d,*head,*p;
a.num = 8; a.next = &b; b.num = 6; b.next = &c;
c.num = 4; c.next = &d; d.num = 2; d.next = 0; head = &a;
head = inverse(head);
head = insert_node(head,7);
head = delete_node(head,2);
}