已知:链表头head, 第一个节点为head->pNext
方法:
逆置操作的空间复杂度和时间复杂度:
1)空间复杂度是o(2),2个辅助指针:Node* curNode和Node* nextNode;
2)时间复杂度是o(n),n是链表的节点总数。
CMyList类实现链表的封装
1)创建链表
2)逆置链表
3)打印链表
4)析构时自动释放链表
main函数实现
1)程序通过argv(只)接收数字(int)的链表数据
2)然后根据接收的数字,通过CMyList对象创建内部链表
3)打印链表
4)逆置链表
5)打印逆置后的链表
6)退出程序。
#ifndef __BLUESKYJOYN_REVERSELIST_H__
#define __BLUESKYJOYN_REVERSELIST_H__
#include <stdio.h>
#include <iostream>
using namespace std;
namespace BlueSkyJoyn {
typedef int DataType;
struct Node
{
Node(DataType value, struct Node* next):data(value), pNext(next){}
DataType data;
struct Node* pNext;
};
class CMyList
{
public:
CMyList();
~CMyList();
Node* create(DataType* array, int count);
Node* getHead();
Node* reverse();
void print();
public:
void destroy();
private:
struct Node* m_head;
};
}
#endif
#include "ReverseList.h"
#include <assert.h>
#include <stdlib.h>
namespace BlueSkyJoyn {
CMyList::CMyList():m_head(NULL){}
CMyList::~CMyList()
{
destroy();
}
void CMyList::destroy()
{
if (m_head != NULL)
{
struct Node *cur = m_head->pNext;
while(cur != NULL)
{
struct Node* tmp = cur->pNext;
delete cur;
cur = tmp;
}
delete m_head;
m_head = NULL;
}
}
Node* CMyList::create(DataType array[], int count)
{
if (array == NULL || count == 0)
{
return NULL;
}
destroy();
m_head = new struct Node(0, NULL);
assert(m_head != NULL);
m_head->pNext = NULL;
struct Node* tail = NULL;
for (int i = 0; i < count; ++i)
{
struct Node *node = new struct Node(array[i], NULL);
if (i > 0)
tail->pNext = node;
else
m_head->pNext = node;
tail = node;
tail->pNext = NULL;
}
}
Node* CMyList::getHead()
{
return m_head;
}
Node* CMyList::reverse()
{
if (!m_head)
{
return NULL;
}
struct Node* curNode = m_head->pNext;
struct Node* nextNode = NULL;
m_head->pNext = NULL;
while(curNode != NULL)
{
nextNode = curNode->pNext;
curNode->pNext = m_head->pNext;
m_head->pNext = curNode;
curNode = nextNode;
}
cout<<endl;
return m_head;
}
void CMyList::print()
{
if (!m_head)
{
cout<<"list is void!"<<endl;
return;
}
struct Node* tmp = m_head->pNext;
while(tmp)
{
cout<<tmp->data<<" ";
tmp = tmp->pNext;
}
cout<<endl;
}
}
using namespace BlueSkyJoyn;
int main(int args, char* argv[])
{
if (args < 2)
{
cout<<"usage:list 1 2 3 4"<<endl;
return 1;
}
CMyList list;
int *array = new int[args - 1];
assert (array != NULL);
for (int i = 0; i < args - 1; ++i)
{
if (!isdigit(*argv[i + 1]))
{
cout<<"make sure data type of list-node is int!"<<endl;
return 0;
}
array[i] = atoi(argv[i + 1]);
}
list.create(array, args - 1);
list.print();
list.reverse();
list.print();
delete []array;
array = NULL;
return 0;
}
运行测试:
1)容错测试
2)功能测试验证
通过测试实现逆置链表的基本功能。
(END)