单链表操作的实现,包括初始化,插入,删除,遍历,排序,归并等。为了方便,使用了带头结点的单链表。注意,单链表的局限之处在于只能向后继方向进行遍历,所以在进行插入和删除操作时要找到目标结点的前驱结点。这个比较关键。其他的细节就比较简单了。
代码如下:
// LinkList.cpp : 定义控制台应用程序的入口点。
//带头结点的单链表
#include "stdafx.h"
#include <iostream>
#include <algorithm>
#include <cstdlib>
#include <vector>
using namespace std;
typedef struct LNode {
int data;
LNode* next;
}LNode, *LinkList;
//取第i个位置的元素
bool getElem(const LinkList& L, int pos, int& e)
{
LNode* p = L;
int j = 0;
while (p&&j<pos - 1)
{
p = p->next;
++j;
}
if (!p || j>pos - 1)
return false;
e = p->next->data;
return true;
}
//插入元素
bool insertList(LinkList& L, int pos, int e)
{
LNode* p = L;
int j = 0;
//找到插入位置
while (p&&j<pos - 1)
{
p = p->next;
++j;
}
if (!p || j>pos - 1) //插入位置大于表长或小于1
return false;
LNode* temp = (LNode*)malloc(sizeof(LNode));
temp->data = e;
temp->next = p->next;
p->next = temp;
return true;
}
//删除元素并返回
bool removeList(LinkList& L, int pos, int& e)
{
LNode* p = L;
int j = 0;
//找到待删除元素的前驱
while (p&&j<pos - 1)
{
p = p->next;
++j;
}
if (!p || j>pos - 1)
return false;
LNode* q = p->next;
p->next = q->next;
e = q->data;
free(q);
return true;
}
//逆序建立表
void createList(LinkList& L)
{
L = (LNode*)malloc(sizeof(LNode));
L->next = NULL;
int n;
//逆序插入
while (cin >> n)
{
insertList(L, 1, n);
}
}
void outputList(const LinkList& L)
{
LNode* p = L;
while (p->next)
{
p = p->next;
cout << p->data << endl;
}
cout << endl;
}
void sortList(LinkList& L)
{
vector<int> s;
LNode* p = L;
p = p->next;
while (p)
{
s.push_back(p->data);
p = p->next;
}
sort(s.rbegin(), s.rend());
p = L;
p = p->next;
while (p && !s.empty())
{
p->data = s.back();
s.pop_back();
p = p->next;
}
}
void mergeList(LinkList& La, LinkList& Lb, LinkList& Lc)
{
LNode* pa = La->next;
LNode* pb = Lb->next;
Lc = La;
LNode* pc = Lc;
while (pa&&pb)
{
if (pa->data<pb->data)
{
pc->next = pa;
pc = pa;
pa = pa->next;
}
else
{
pc->next = pb;
pc = pb;
pb = pb->next;
}
}
pc->next = pa ? pa : pb;
free(Lb);
}
int main()
{
LinkList L;
createList(L);
cout << "Init:\n";
outputList(L);
insertList(L, 3, 1000);
cout << "Insert:\n";
outputList(L);
int e;
removeList(L, 3, e);
cout << "Remove:\n";
outputList(L);
sortList(L);
cout << "Sort:\n";
outputList(L);
cout << "La:\n";
for (int i = 1; i <= 5; i++)
{
getElem(L, i, e);
cout << e << endl;
}
cout << endl;
LinkList L2;
LinkList L3;
L2 = (LNode*)malloc(sizeof(LNode));
L2->next = (LNode*)malloc(sizeof(LNode));
L2->next->data = -10;
L2->next->next = (LNode*)malloc(sizeof(LNode));
L2->next->next->data = 22;
L2->next->next->next = NULL;
cout << "Lb:\n";
for (int i = 1; i <= 2; i++)
{
getElem(L2, i, e);
cout << e << endl;
}
cout << endl;
mergeList(L, L2, L3);
cout << "Merge:\n";
outputList(L3);
system("pause");
return 0;
}