单向链表的操作
创建链表,逆序链表,合并链表
// ConsoleApp.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
typedef struct Node
{
int m_data;
Node* m_pNext;
Node(int data, Node* pNext) {
this->m_data = data;
this->m_pNext = pNext;
}
}TNODE;
//1,2,3,4,5,6,7
//7,6,5,4,3,2,1
//逆序链表
Node* ReverseList(Node* pList)
{
Node* pHead = pList;
if (pHead == nullptr)
{
return pHead;
}
Node* pPrev = nullptr;
Node* pOperator = pHead;
Node* pOperatorNext = pOperator->m_pNext;
while (pOperator) {
pOperator->m_pNext = pPrev;
pPrev = pOperator;
pOperator = pOperatorNext;
if (pOperator) {
pOperatorNext = pOperator->m_pNext;
}
}
return pPrev;
}
void PrintList(Node* pList) {
Node* node = pList;
printf("List= ");
while (node) {
printf(" %d ,", node->m_data);
node = node->m_pNext;
}
printf("\n");
}
//逆序链表
void testReverseList()
{
Node* head = nullptr;
Node* pPrev = nullptr;
for (int i = 0; i < 20; i++) {
Node* node = new Node(i, NULL);
if (pPrev)
{
pPrev->m_pNext = node;
}
else {
head = node;
}
pPrev = node;
}
PrintList(head);
Node* reHead = ReverseList(head);
printf("afterReverse\n");
PrintList(reHead);
}
Node* CreateList(int arry[] , int n_size)
{
Node* pHead = nullptr;
Node* pPrev = nullptr;
for (int i = 0; i < n_size; ++i)
{
Node* pNode = new Node(arry[i], NULL);
if (i == 0)
{
pHead = pNode;
}
if (pPrev)
{
pPrev->m_pNext = pNode;
}
pPrev = pNode;
}
return pHead;
}
Node* MergeList(Node* pList1, Node* pList2) {
Node* pNewList = nullptr;
if (pList1&& pList2)
{
Node* p1 = pList1;
Node* p2 = pList2;
Node* pPrev1 = nullptr;
Node* pPrev2 = nullptr;
if (pList1->m_data <= pList1->m_data)
pNewList = pList1;
else
pNewList = pList2;
int flag = 0;
//1,3,4,6,9,10
//5,6,7,8,11,12
while (true)
{
if ( p1->m_data <= p2->m_data)
{
if (flag == 2)
{
pPrev2->m_pNext = p1;
flag = 0;
}
pPrev1 = p1;
p1 = p1->m_pNext;
flag = 1;
if (p1 == nullptr)
{
pPrev1->m_pNext = p2;
break;
}
}
else {
if (flag == 1) {
pPrev1->m_pNext = p2;
flag = 0;
}
pPrev2 = p2;
p2 = p2->m_pNext;
flag = 2;
if (p2 == nullptr)
{
pPrev2->m_pNext = p1;
break;
}
}
}
}
return pNewList;
}
//合并2个链表
void testMergeList() {
int aray1[] = { 1,3,4,6,9,10 };
int aray2[] = { 2,5,6,7,8,11,12 };
Node* pList1 = CreateList(aray1, sizeof(aray1) / sizeof(int));
Node* pList2 = CreateList(aray2, sizeof(aray2) / sizeof(int));
PrintList(pList1);
PrintList(pList2);
Node* newList = MergeList(pList1, pList2);
PrintList(newList);
}
int main() {
testMergeList();
system("pause");
return 0;
}