以下都是對單鏈表一些簡單的應用和對一些簡單問題的解決方案。
代碼如下:
#define _CRT_SECURE_NO_WARNINGS //vs2013中需要加的一個宏!
#include<iostream>
#include<string.h>
#include<assert.h>
typedef int DateType;
typedef struct SListNode
{
DateType data;
struct SListNode *next;
}SListNode;
打印節點,代碼如下:
void PrintfSlist(SListNode *&pHead) //打印節點
{
SListNode *newHead = pHead;
if (newHead == NULL)
{
return;
}
while (newHead)
{
printf("%d ", newHead->data);
newHead = newHead->next;
}
}
2.創建節點,代碼如下:
SListNode* _BuyNode(DateType x) //創建節點
{
SListNode*pHead = (SListNode*)malloc(sizeof(SListNode));
pHead->data = x;
pHead->next = NULL;
return pHead;
}
3.尾插法,代碼如下:
void PushBack(SListNode *&pHead, DateType x) //尾插
{
if (pHead == NULL)
{
pHead = _BuyNode(x);
}
else
{
SListNode *tail = pHead;
while (tail->next != NULL)
{
tail = tail->next;
}
tail->next = _BuyNode(x);
}
}
測試代碼如下:
void Test1()
{
SListNode *seq = NULL;
PushBack(seq, 1);
PushBack(seq, 2);
PushBack(seq, 3);
PushBack(seq, 4);
PushBack(seq, 5);
PushBack(seq, 6);
PushBack(seq, 7);
PushBack(seq, 8);
PushBack(seq, 9);
PushBack(seq, 10);
PushBack(seq, 11);
PrintfSlist(seq);
}
4.尾出法,代碼如下:
void PopBack(SListNode *&pHead) //尾出
{
if (pHead == NULL)
{
return;
}
else if (pHead->next == NULL)
{
free(pHead);
pHead = NULL;
}
else
{
SListNode *prev = pHead;
SListNode *cur = pHead->next;
while (cur->next != NULL)
{
prev = prev->next;
cur = cur->next;
}
free(cur);
prev->next = NULL;
}
}
測試程序如下:
void Test2()
{
SListNode *seq = NULL;
PushBack(seq, 1);
PushBack(seq, 2);
PushBack(seq, 3);
PushBack(seq, 4);
PushBack(seq, 5);
PrintfSlist(seq);
printf("\n");
PopBack(seq);
PrintfSlist(seq);
printf("\n");
PopBack(seq);
PrintfSlist(seq);
printf("\n");
PopBack(seq);
PrintfSlist(seq);
printf("\n");
PopBack(seq);
PrintfSlist(seq);
printf("\n");
PopBack(seq);
PrintfSlist(seq);
printf("\n");
}
5.頭插和頭出,代碼如下:
void PushFront(SListNode *&pHead, DateType x) //頭插
{
SListNode *newpHead = _BuyNode(x);
newpHead->next = pHead;
pHead = newpHead;
}
void PopFront(SListNode *&pHead) //頭出
{
if (pHead == NULL)
{
return;
}
else
{
SListNode *tmp = pHead->next;
free(pHead);
pHead = tmp;
}
}
測試程序如下:
void Test3()
{
SListNode *seq = NULL;
PushFront(seq, 1);
PushFront(seq, 2);
PushFront(seq, 3);
PushFront(seq, 4);
PushFront(seq, 5);
PrintfSlist(seq);
printf("\n");
PopFront(seq);
PrintfSlist(seq);
printf("\n");
PopFront(seq);
PrintfSlist(seq);
printf("\n");
PopFront(seq);
PrintfSlist(seq);
printf("\n");
PopFront(seq);
PrintfSlist(seq);
printf("\n");
PopFront(seq);
PrintfSlist(seq);
printf("\n");
}
6.找出某個節點並返回節點的地址
SListNode * Find(SListNode *& pHead, DateType x) //找出某個節點並返回節點的地址
{
assert(pHead);
SListNode *NewHead = pHead;
while (NewHead)
{
if (NewHead->data == x)
{
return NewHead;
}
NewHead = NewHead->next;
}
return NULL;
}