尾指針是相對於頭指針而言的,形式與頭指針相同,內容指向鍊表的最後一個節點。
基本介紹
- 中文名:尾指針
- 套用:數據結構
介紹
代碼
#include <stdio.h>
#include <stdlib.h>
#define ElementType int
struct ListNode
{
ElementType Element;
struct ListNode *Next;
};
typedef struct
{
struct ListNode *Head;
struct ListNode *Tail;
} List, *pList;
int InsertTail( ElementType X, pList L ) //尾部插入元素
{
struct ListNode *newP;
if ( (newP = malloc(sizeof(struct ListNode))) == NULL )
{
perror("OUT OF SPACE!");
return -1;
}
newP->Element = X;
newP->Next = NULL;
L->Tail->Next = newP;
L->Tail = newP;
if ( L->Head->Next == NULL)
{
L->Head->Next = L->Tail;
}
return 0;
}
int InsertHead( ElementType X, pList L ) //頭部插入元素
{
struct ListNode *newP;
if ( (newP = malloc(sizeof(struct ListNode))) == NULL )
{
perror("OUT OF SPACE!");
return -1;
}
newP->Element = X;
newP->Next = L->Head->Next;
L->Head->Next = newP;
return 0;
}
int main()
{
pList L;
if ( (L = malloc(sizeof(List))) == NULL )
{
perror("OUT OF SPACE!");
return -1;
}
if ( (L->Head = malloc(sizeof(struct ListNode))) == NULL )
{
perror("OUT OF SPACE!");
return -1;
}
L->Head->Next = NULL; //初始化
L->Tail = L->Head;
InsertTail( 10, L );
InsertTail( 11, L );
InsertTail( 12, L ); //三次尾部插入
InsertHead( 13, L );
InsertHead( 14, L ); //兩次頭部插入
InsertTail( 15, L );
InsertTail( 16, L ); //兩次尾部插入
while( L->Head->Next != NULL ) //遍歷輸出
{
printf("%d ", L->Head->Next->Element);
L->Head = L->Head->Next;
}
puts("");
return 0;
}
jimmy@MyPet:~/code/learnc$ make
gcc -Wall -g -o test test.c -std=c99
jimmy@MyPet:~/code/learnc$ ./test
14 13 10 11 12 15 16
