c++單向連結串列
阿新 • • 發佈:2019-01-06
#include <iostream>
#include <time.h>
using std::cout;
using std::endl;
struct Node
{
int data;
struct Node* next;
};
一、建立連結串列
Node * createList()
{
Node *head = new Node;
if (NULL == head)
exit(-1);
head->next = NULL;
return head;
}
二、尾插法
void inisertListTail (Node *head, int num)
{
while (head->next!= NULL)
{
head = head->next;
}
Node *t = head;
Node *cur = new Node;
if (NULL == cur)
exit(-1);
cur->data = num;
t->next = cur;
t = cur;
t->next = NULL;
}
二、頭插法
void insertListHead(Node *head, int nums)
{
Node *cur = new Node;
if (NULL == cur)
exit(-1);
cur->data = nums;
cur->next = head->next;
head->next = cur;
}
三、求連結串列長度
int lengthList(Node *head)
{
head = head->next;
int i = 0;
while (head)
{
head = head->next;
i++;
}
return i;
}
四、查詢
Node *searchList(Node *head, int findData)
{
head = head->next;
while (head)
{
if (head->data == findData)
break;
head = head->next;
}
return head;
}
五、刪除
void deleteData(Node *head, Node *pfind)
{
if (pfind->next == NULL)
{
while (head->next != pfind) //方法1 找到前一個
{
head = head->next;
}
head->next = pfind->next;
delete(pfind);
pfind = NULL;
}
else
{
Node *t = pfind->next;
pfind->data = pfind->next->data; //優化後(替換)
pfind->next = pfind->next->next;
delete(t);
}
}
六、排序(換值)
void popSortList(Node *head) //交換資料
{
int n=0;
head = head->next;
Node *t = NULL;
int nums = lengthList(head);
for (int i = 0;i < nums - 1;i++)
{
t = head;
for (int j = 0;j < nums - 1 - i;j++)
{
if (t->data < t->next->data)
{
n = t->data;
t->data = t->next->data;
t->next->data = n;
}
t = t -> next;
}
}
}
排序(換指標)
void popSortList2(Node *head)
{
Node *prep = NULL;
Node *p = NULL;
Node *q=NULL;
Node *t = NULL;
int nums = lengthList(head);
for (int i = 0;i < nums - 1;i++)
{
prep = head;
p = head->next;
q = p->next;
for (int j = 0;j < nums - 1 - i;j++)
{
if (p->data > q->data)
{
prep->next = q;
p->next = q->next;
q->next = p;
t = q;
q = p;
p = t;
}
prep = prep->next;
p = p->next;
q = q->next;
}
}
}
七、連結串列逆置
void reverseList(Node *head)
{
Node *t = NULL;
head->next = NULL;//將連結串列分為兩部分。
Node *cur = head->next;
while (cur)
{
t = cur;
cur = cur->next;
t->next = head->next;
head->next = t;
}
}
八、刪除連結串列
void deleteList(Node *head)
{
Node *t = NULL;
while (head)
{
t = head->next;
delete(head);
head = t;
}
}