链表的基本操作

这是我第一篇博文。准备写成一个系列,关于数据结构的。今天开始最简单的,链表。

定义:

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;

}

 

转载于:https://www.cnblogs.com/zhangweijie/archive/2013/03/30/2988017.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值