#include<iostream>
#include<stdio.h>
typedef struct Node
{//定义一个结点
int data;
Node *next;
Node(const int& dataVal,Node* nextVal=NULL):data(dataVal),next(nextVal) {}
Node(Node* nextVal=NULL):next(nextVal){}
}LNode,*LinkList;
class LList
{
public:
LList(int size);
~LList();
void clear();
void print(LNode* head) ;
void insert(const int& it);
void append(const int& it);
LNode* createLinkList(int n);
LNode* bubbleSortLinkList(LNode* headNode);
int length();
private:
Node* head;
Node* tail;
Node* curr;
int linkListCnt;
};
LList::LList(int size)
{
curr = head = tail = new Node();
linkListCnt = 0;
}
LList::~LList()
{
while (head!=NULL)
{
curr = head;
head = head->next;
delete curr;
}
}
void LList::clear()
{
while (head != NULL)
{
curr = head;
head = head->next;
delete curr;
}
curr = head = tail = new Node();
linkListCnt = 0;
}
void LList::insert(const int& it)
{
curr->next = new LNode(it, curr->next);
if (tail == curr)
tail = curr->next;
linkListCnt++;
}
void LList::append(const int& it)
{
tail->next = new Node(it, NULL);
tail = tail->next;
linkListCnt++;
}
int LList::length() { return linkListCnt; }
void LList::print(LNode* head)
{
LNode* p = head->next;
while (p)
{
std::cout << p->data << " " ;
p = p->next;
}
std::cout << std::endl;
}
LNode* LList::createLinkList(int n)
{
int value;
linkListCnt = 0;
for (int i = 0; i < n; ++i)
{
printf("请输入链表中的第%d个数:", i);
scanf_s("%d", &value);
tail->next = new Node(value, NULL);
tail = tail->next;
linkListCnt++;
}
return head;//返回链表
}
LNode* LList::bubbleSortLinkList(LNode* headNode)
{
LNode* tempNode1 = NULL;
LNode* tempNode2 = NULL;
if (headNode == tail)
return NULL;
for (tempNode1= headNode->next; tempNode1 != NULL; tempNode1 = tempNode1->next)
{
for (tempNode2 = headNode->next; tempNode2 != NULL; tempNode2 = tempNode2->next)
{
if (tempNode1->data < tempNode2->data)
{
int temp = tempNode1->data;
tempNode1->data = tempNode2->data;
tempNode2->data = temp;
}
}
}
return headNode;
}
LNode* mergeLinkList(LNode* list1Node, LNode* list2Node)
{
LNode* tempNode = list1Node;
for (; tempNode->next != NULL; tempNode = tempNode->next) { ; }
tempNode->next = list2Node->next;
list2Node->next = NULL;//避免被第二次析构
return list1Node;
}
#include "stdafx.h"
#include"List.h"
int main()
{
LList list1(10),list2(10);
LNode* list1Node = list1.createLinkList(5);
LNode* list2Node = list2.createLinkList(5);
std::cout << "两个链表连接后的链表:" << std::endl;
LNode* tempNode = mergeLinkList(list1Node, list2Node);
list1.bubbleSortLinkList(tempNode);
list1.print(tempNode);
return 0;
}
由于对数据结构较为陌生,编写的代码水平有限,望得到指点改进。进行过简单的测试,可行,也许在某些特殊情况条件下还得对代码进行适当的修正!