反转单链表_字符串_数字

没啥太多技巧,反转就好了。单链表的时候要注意,while中不能将pCur的next指向NULL,否则的话,pNext的next就白指了。

#include "stdafx.h"
#include <iostream>
#include<cstring>
#include <vector>
#include <assert.h>
using namespace std;

struct ListNode
{
    int m_key;
    ListNode* next;
};


void createList(ListNode* &pHead)
{
    pHead = new ListNode;
    pHead->m_key= 0;
    pHead->next = NULL;
    ListNode* p = pHead;
    for(int i=1; i<10; i++)
    {
        ListNode* pNewNode = new ListNode;
        pNewNode->m_key = i;
        pNewNode->next = NULL;
        p->next = pNewNode;
        p = pNewNode;
    }
}

void destoryList(ListNode* pHead)
{
    assert(pHead!=NULL);
    ListNode* pNext = pHead->next;
    while(pNext != NULL)
    {
        delete pHead;
        pHead = pNext;
        pNext = pHead->next;
    }
    delete pHead;
    pHead = NULL;
    return;
}


ListNode* reverseList(ListNode* pHead)
{
    assert(pHead!=NULL);
    if(pHead->next == NULL)
        return pHead;
    ListNode* pNext = pHead->next;
    ListNode* pCur = pHead;
    pCur->next = NULL;
    while (pNext!=NULL)
    {
        ListNode* pTemp = pNext->next;
        pNext->next = pCur;
        pCur = pNext;
        pNext = pTemp;
    }
    return pCur;
}

void reverseString(char* pStr)
{
    assert(pStr!=NULL);
    int length = strlen(pStr);
    if(length == 0) return;
    char* pBegin = pStr,*pEnd = pStr+length-1;
    while(pBegin<pEnd)
    {
        char temp = *pBegin;
        *pBegin = *pEnd;
        *pEnd = temp;
        pBegin++;
        pEnd--;

    }
}


int reverseInt(int num)
{
    int reverseNum = 0;
    while (num!=0)
    {
        int res = num%10;
        reverseNum = reverseNum * 10 +res;
        num /= 10;
    }
    return reverseNum;
}


int main()
{
    // 反转单链表
    ListNode* head = NULL;
    createList(head);
    head = reverseList(head);
    ListNode* p = head;
    while(p)
    {
        cout<<p->m_key<<" ";
        p=p->next;
    }
    cout<<endl;
    destoryList(head);

    // 反转字符串
    char* str = "0123456789";
    char* pStr = (char*)malloc((strlen(str)+1)*sizeof(char));
    strcpy(pStr,str);
    reverseString(pStr);
    cout<<pStr<<endl;


    // 反转数字
    int n = 123456789;
    cout<<reverseInt(n)<<endl;
}

输出的结果:

9 8 7 6 5 4 3 2 1 0
9876543210
987654321

原文地址:https://www.cnblogs.com/cyttina/p/2740408.html