首页 > 其他 > 详细

CPP:Reverse Linklist

时间:2020-04-27 22:51:44      阅读:47      评论:0      收藏:0      [点我收藏+]
#include "stdafx.h"
#include <iostream>

typedef struct LinkList {
    int data;
    struct LinkList *next;
} LinkList_t;


LinkList *Reverse(LinkList_t *pHead) {
    if (NULL == pHead || NULL == pHead->next) {
        return pHead;
    }

    // pTail
    // pHead---->begNode---->nextNode
    LinkList *pTail = pHead
           , *pBegNode = pHead->next
           , *pNextNode = NULL
    ;

    while (pBegNode) {
         pNextNode = pBegNode->next; // remember the second half link 

        // 1:headNode<--2:BegNode
        // 1=still => 1=move & 2:still; 2=move & 3:still
        pBegNode->next = pHead;
        pHead = pBegNode;
        pBegNode = pNextNode;
    }

    pTail->next = NULL; // cut off infinite recursion
    return pHead;
}

void printLinklist(LinkList_t *pHead) {
    while (pHead) {
        std::cout << pHead->data << std::endl;
        pHead = pHead->next;
    }
}

int _tmain(int argc, _TCHAR* argv[]) {
    LinkList_t 
        n5 = {500, NULL}
      , n4 = {400, &n5}
      , n3 = {300, &n4}
      , n2 = {200, &n3}
      , n1 = {100, &n2}
      , *pHead = &n1
    ;

    printLinklist(pHead);
    pHead = Reverse(pHead);
    printLinklist(pHead);
}

 

CPP:Reverse Linklist

原文:https://www.cnblogs.com/xinyueliu/p/12790586.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!