1. 程式人生 > >C++ 單鏈表的 就地逆置 ,以及基本操作

C++ 單鏈表的 就地逆置 ,以及基本操作

#include "stdafx.h"
#define  sub(a,b) a-b //沒用
#include <iostream>
using namespace std;
struct node
{
	int a;
	node * next;
};
int _tmain(int argc, _TCHAR* argv[])
{
	//int x=sub(3,8);
  
     node * createList();
	cout<<"開始建立連結串列"<<endl;
	node *pbeg=createList();
	node *p=pbeg;
	while (p)
	{
		cout<<"本節點數值是:"<<p->a<<endl;
		p=p->next;
	}
	cout<<"請輸入要刪除的元素"<<endl;
	int loc;
	cin>>loc;
	node * delEle(node * pbeg,int loc);
	node * ru;
	ru=delEle(pbeg,loc);
	cout<<"刪除元素後的連結串列的遍歷結果"<<endl;
	while (ru)
	{
		cout<<"本節點數值是:"<<ru->a<<endl;
		ru=ru->next;
	}

	node * rt(node * pbeg);//宣告函式
	node * r=rt(pbeg);
	cout<<"變為逆序後的連結串列的遍歷結果"<<endl;
	while (r)
	{
		cout<<"本節點數值是:"<<r->a<<endl;
		r=r->next;
	}
	return 0;
}

//使單鏈表變為原來的逆序
node * rt(node * pbeg)
{
	node * pPre=pbeg;
	node * pCur=pPre->next;
	node * pNext=NULL;

	while(pCur)
	{
		pNext=pCur->next;
		pCur->next=pPre;
		pPre=pCur;
		pCur=pNext;
	}
	pbeg->next=NULL;
	return pPre;//返回新的表頭節點
}
//建立單鏈表
node * createList()
{
	node * pbeg=new node;
	(*pbeg).a=1;
	node * p=pbeg;
	int j=9;
	node * q;
	while(j>0)
	{
		j--;
		q=new node;
		cout<<"請輸入一個整數"<<endl;
		int temp;
		cin>>temp;
		q->a=temp; //賦值

		p->next=q;
		p=q;
	}
	p->next=NULL;
	return pbeg;
}
//刪除指定元素的節點;
node * delEle(node * pbeg,int ele)
{
	node * pPre=pbeg;
	node *pCur=pbeg->next;

	if (pbeg->a==ele)
		pbeg=pbeg->next;
	else
	{
		while (pCur->a!=ele&&pCur)
		{
			pPre=pCur;
			pCur=pCur->next;
		}
		pPre->next=pCur->next;
	}
	return pbeg;
}