对单链表的一些操作
2014-09-07 10:30
281 查看
#include "stdafx.h" #include<string> #include<iostream> #include<stack> using namespace std; struct ListNode { //结点类型 int m_nValue; ListNode* m_pNext; }; void AddToTail(ListNode** pHead,int value) { //尾插法 ListNode* pNew = new ListNode(); pNew->m_nValue = value; pNew->m_pNext = NULL; if(*pHead==NULL) { *pHead = pNew; }else { ListNode *pNode = *pHead; while(pNode->m_pNext !=NULL) { pNode =pNode->m_pNext; } pNode ->m_pNext = pNew; } } void AddToHead(ListNode** pHead,int value) { //头插法 ListNode *pNew = new ListNode; pNew->m_nValue = value; pNew->m_pNext = NULL; if(*pHead==NULL) { *pHead =pNew; } else { ListNode *Head = *pHead; pNew->m_pNext = Head; (*pHead) = pNew; } } void showNode(const ListNode *Head) { int count = 0; while(Head!=NULL) { cout<<Head->m_nValue<<" "; Head=Head->m_pNext; count++; } cout<<endl<<"元素个数:"<<count<<endl;; } void InsertNodeByArray(int *arr,int length,ListNode** Head) { //通过数组进行插入元素 for(int i =0;i!=length;++i) { AddToTail(Head,arr[i]); } } void RemoveNode(ListNode** Head,int value) { //删除元素内容是value的所有结点,注意第一个元素和最后一个元素 if(*Head==NULL) { cout<<"Can not Find the value:"<<value<<endl; return; } ListNode *pHead = *Head; ListNode *pDelete; if(pHead->m_nValue==value) { pDelete = *Head; (*Head)=pDelete ->m_pNext; delete pDelete; pDelete = NULL; return; } else { while(pHead->m_pNext!=NULL){ while(pHead->m_pNext!=NULL&&pHead->m_pNext->m_nValue!=value) { pHead=pHead->m_pNext; } if(pHead->m_pNext!=NULL&&pHead->m_pNext->m_nValue==value) { cout<<"Find The Node,The value is:"<<value<<endl; pDelete =pHead->m_pNext; if(pDelete->m_pNext!=NULL){ pHead->m_pNext=pDelete->m_pNext; pHead=pHead->m_pNext; delete pDelete; pDelete = NULL; } else { pHead->m_pNext=NULL; delete pDelete; pDelete = NULL; return; } } } } } void resverseList(ListNode *Node) { if(Node!=NULL){ if(Node->m_pNext!=NULL) { resverseList(Node->m_pNext); } cout<<Node->m_nValue<<" "; } //递归实现反向遍历链表 } void resverseList_Stack(ListNode *Node) { //用stack逆向输出. stack<ListNode*> sNode; ListNode *pNode = Node; while(pNode!=NULL) { sNode.push(pNode); pNode=pNode->m_pNext; } while(!sNode.empty()) { cout<< sNode.top()->m_nValue<<" "; sNode.pop(); } //递归实现反向遍历链表 } int _tmain(int argc, _TCHAR* argv[]) { const int len = 3; ListNode *Head=NULL; int a[len]={1,2,3}; InsertNodeByArray(a,len,&Head); showNode(Head); RemoveNode(&Head,1); showNode(Head); resverseList(Head); cout<<endl; resverseList_Stack(Head); return 0; }