这是我第一篇博文。准备写成一个系列,关于数据结构的。今天开始最简单的,链表。
定义:
1 struct ListNode{ 2 int m_nValue; 3 ListNode* m_pNext; 4 };
向链表的末尾插入节点:
PS:由于此处头指针可能改变(NULL的时候),所以传入了指向头结点指针的指针。
1 void AddToTail(ListNode **pHead, int mValue){ 2 ListNode* pNew = new ListNode(); 3 pNew->m_nValue = mValue; 4 pNew->m_pNext = NULL; 5 if(*pHead == NULL){ 6 *pHead = pNew; 7 }else{ 8 ListNode* pNode = *pHead; 9 while(pNode->m_pNext!=NULL){ 10 pNode = pNode->m_pNext; 11 } 12 pNode->m_pNext = pNew; 13 } 14 }
好,测试一下这个功能。这里用了一个遍历输出链表的方法:
#include <iostream> using namespace std;
void PrintList(ListNode *pHead){
while(pHead!=NULL){
cout<<pHead->m_nValue<<" ";
pHead = pHead->m_pNext;
}
cout<<endl;
}
int main(){ ListNode *pList = NULL; for(int i=0 ;i<10; i++){ AddToTail(&pList, i); PrintList(pList); } }
再来一个从尾到头打印单链表的函数:
#include<stack> void PrintListReversingly(ListNode *pHead){ stack<int> nValues; while(pHead!=NULL){ nValues.push(pHead->m_nValue); pHead=pHead->m_pNext; } while(!nValues.empty()){ int value = nValues.top(); cout<<value<<" "; nValues.pop(); } cout<<endl; }
反转单链表
ListNode* ReverseList(ListNode *pHead){ ListNode* pNode = pHead; ListNode* pPre = NULL; while(pNode != NULL){ ListNode *pNext = pNode->m_pNext; pNode->m_pNext=pPre; pPre = pNode; pNode= pNext; } return pPre; }