單向鏈表節點定義:
typedef struct node
{
int data;
struct node *next;
}Node,*pNode;
雙向鏈表節點定義:
typedef struct node
{
int data;
struct node *next;
struct node *pre;
}Node,*pNode;
鏈表逆序
非遞歸方法:
pNode RevertList(pNode head)
{
if ((head == NULL) || (head->next == NULL))
return head;
pNode p1 = head;
pNode p2 = p1->next;
pNode p3 = p2->next;
p1->next = NULL;
while(p3 != NULL)
{
p2->next = p1;
p1 = p2;
p2 = p3;
p3 = p3->next;
}
p2->next = p1;
head = p2;
return head;
}
遞歸方法:
pNode RevertList(pNode head)
{
pNode p1 = NULL;
if ( (head == NULL) || (head->next == NULL))
return head;
p1 = RevertList(head->next);
head->next->next = head;
head->next = NULL;
return p1;
}
將2個有序的鏈表合併成一個有序鏈表
非遞歸方法:pNode MergeList(pNode head1, pNode head2)
{
if (head1 == NULL)
return head2;
if (head2 == NULL)
return head1;
pNode p1 = NULL;
pNode p2 = NULL;
pNode head = NULL;
if (head1->data < head2->data)
{
head = head1;
p1 = head1->next;
p2 = head2;
}
else
{
head = head2;
p1 = head1;
p2 = head2->next;
}
pNode curNode = head;
while((p1 != NULL) && (p2 != NULL))
{
if (p1->data < p2->data)
{
curNode->next = p1;
curNode = p1;
p1 = p1->next;
}
else
{
curNode->next = p2;
curNode = p2;
p2 = p2->next;
}
}
if (p1 == NULL)
curNode->next = p2;
else
curNode->next = p1;
return head;
}
遞歸方法:
pNode MergeList(pNode head1, pNode head2)
{
if (head1 == NULL)
return head2;
if (head2 == NULL)
return head1;
pNode head = NULL;
if (head1->data < head2->data)
{
head = head1;
head->next = MergeList(head1->next, head2);
}
else
{
head = head2;
head->next = MergeList(head1, head2->next);
}
return head;
}
判斷一個單鏈表是有環的
bool CheckLoop(const pNode head)
{
if (head == NULL)
return false;
pNode low = head;
pNode fast = head->next;
while((fast != NULL) && (fast->next != NULL))
{
if (low == fast)
return true;
low = low->next;
fast = fast->next->next;
}
return false;
}