数据结构与算法分析 c++11 练习3.2 通过只调整链(而不是数据)来交换两个相邻的元素

练习3.2 通过只调整链(而不是数据)来交换两个相邻的元素,分别使用


a. 单链表。

b. 双链表。


singlyList.h

#pragma once
#include 
struct ListNode {
	int value;
	ListNode * pNext;
};

void addListNode(ListNode * & p, int v) {
	if (p==NULL) {
		ListNode * pTem = new ListNode;
		pTem->pNext = NULL;
		pTem->value = v;
		p = pTem;
	}
	else
		addListNode(p->pNext, v);
}

void swap(ListNode * & p) {      //chang the neighboring node;  
	if (NULL == p)
		return;

	ListNode * p1;
	ListNode * p2;

	p1 = p->pNext;
	p2 = p1->pNext;

	p1->pNext = p2->pNext;
	p->pNext = p2;
	p2->pNext = p1;
}

void traverse(ListNode * p) {            //traverse the list and output the value  
	while (NULL != p)
	{
		std::cout << p->value << " ";
		p = p->pNext;
	}
	std::cout << std::endl;
	return;
}



doublyList.h

#pragma once

#include 
struct DbListNode {
	int value;
	DbListNode * pNext;
	DbListNode * pPre;
};

DbListNode * pTail;


void addDoublyListNode(DbListNode * & p, int v) {
	if (NULL == p) {
		if (NULL == pTail) {
			DbListNode * pTem = new DbListNode;
			pTem->pNext = NULL;
			pTem->pPre = NULL;
			pTem->value = v;
			p = pTem;
			pTail = pTem;
		}
		else {
			DbListNode * pTem = new DbListNode;
			pTem->pNext = NULL;
			pTem->pPre = pTail;
			pTem->value = v;
			p = pTem;
			pTail = pTem;
		}
	}
	else
		addDoublyListNode(p->pNext, v);
}

void swapDoublyList(DbListNode * & p) {      //chang the neighboring node;  
	if (NULL == p)
		return;

	DbListNode * p1;
	DbListNode * p2;

	p1 = p->pNext;
	p2 = p1->pNext;

	p1->pNext = p2->pNext;
	p2->pNext->pPre = p1;

	p->pNext = p2;
	p2->pPre = p;

	p2->pNext = p1;
	p1->pPre = p2;
}

void printDbList(DbListNode * p) {            //traverse the list and output the value  
	while (NULL != p)
	{
		std::cout << p->value << " ";
		p = p->pNext;
	}
	std::cout << std::endl;
	
	DbListNode * p1 = pTail;
	while (NULL != p1)
	{
		std::cout << p1->value << " ";
		p1 = p1->pPre;
	}
	std::cout << std::endl;
	std::cout << std::endl;
	return;
}


main.cpp

#include "singlyList.h"
#include "doublyList.h"
using namespace std;


ListNode * psHead = NULL;

DbListNode *pdHead = NULL;


int main()
{
	
	// singly List
	cout << "singly List switch test: " << endl;
	addListNode(psHead, 1);
	addListNode(psHead, 2);
	addListNode(psHead, 3);
	addListNode(psHead, 4);
	addListNode(psHead, 5);

	traverse(psHead);
	swap(psHead->pNext);
	traverse(psHead);
	cout << endl << endl;



	cout << "Doubly List switch test: " << endl;
	pTail = NULL;
	addDoublyListNode(pdHead, 1);
	addDoublyListNode(pdHead, 2);
	addDoublyListNode(pdHead, 3);
	addDoublyListNode(pdHead, 4);
	addDoublyListNode(pdHead, 5);

	printDbList(pdHead);
	//swapDoublyList(pdHead);
	swapDoublyList(pdHead->pNext);
	printDbList(pdHead);

	return 0;
}



你可能感兴趣的:(数据结构与算法,数据结构与算法分析,c++11,链表)