#include <stdio.h>
#include <stdlib.h>
#define TRUE 1
#define FALSE 0
typedef int LinkData;
typedef struct _node
{
LinkData data;
struct _node *next;
}Node;
int Insert_Head(Node **h, LinkData data)
{
if (h == NULL)
return FALSE;
Node* node = (Node*)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
return FALSE;
}
node->data = data;
node->next = *h;
*h = node;
return TRUE;
}
int Insert_Last(Node **h, LinkData data)
{
if (h == NULL)
{
return FALSE;
}
Node* node = (Node*)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
return FALSE;
}
node->data = data;
node->next = NULL;
Node * tmp = *h;
if (tmp == NULL)
{
*h = node;
}
else
{
while (tmp->next)
{
tmp = tmp->next;
}
tmp->next = node;
}
return TRUE;
}
int Insert_Pos (Node** h, int pos, LinkData data)
{
if (h == NULL || pos < 1)
return FALSE;
Node* node = (Node*)malloc(sizeof(Node)/sizeof(char));
if (node == NULL)
{
return FALSE;
}
node->data = data;
if (*h == NULL)
{
if (pos != 1)
{
printf ("当前为空表,无法在第 %d 结点处插入数据\n", pos);
free(node);
return FALSE;
}
node->next = NULL;
*h = node;
}
else
{
if (pos == 1)
{
node->next = *h;
*h = node;
}
else
{
int i;
Node *tmp = *h;
for (i = 0; i < pos-2; i++)
{
if (tmp == NULL)
break;
tmp = tmp->next;
}
if (tmp == NULL)
{
printf ("插入位置越界\n");
free(node);
return FALSE;
}
node->next = tmp->next;
tmp->next = node;
}
}
return TRUE;
}
int Delete_Pos(Node** h, int pos)
{
if (h == NULL || *h == NULL || pos < 1)
return FALSE;
Node *tmp = *h;
if (pos == 1)
{
*h = tmp->next;
free(tmp);
}
else
{
int i;
for (i = 0; i < pos-2; i++)
{
if (tmp->next == NULL)
break;
tmp = tmp->next;
}
if (tmp->next == NULL)
{
printf ("删除位置越界\n");
return FALSE;
}
Node* p = tmp->next;
tmp->next = p->next;
free(p);
}
return TRUE;
}
int Reverse_List(Node **h)
{
if (h == NULL || *h == NULL || (*h)->next == NULL)
return FALSE;
Node *pre = *h;
Node *cur = (*h)->next;
Node *tmp;
while (cur)
{
tmp = cur->next;
cur->next = pre;
pre = cur;
cur = tmp;
}
(*h)->next = NULL;
*h = pre;
return TRUE;
}
void Display(Node *h)
{
if (h == NULL)
return;
int count = 0;
while (h)
{
if (count++ % 4 == 0)
printf ("\n");
printf ("%8d", h->data);
h = h->next;
}
printf ("\n");
}
int main()
{
Node * head = NULL;
int i;
for (i = 0; i < 10; i++)
{
Insert_Last(&head, i);
}
#if 0
Insert_Pos(&head, 1, 1000);
Insert_Pos(&head, 10, 2000);
Insert_Pos(&head, 13, 3000);
Insert_Pos(&head, 15, 3000);
Insert_Pos(&head, 0, 1000);
#endif
Display(head);
Reverse_List(&head);
Display(head);
return 0;
}