面试题-链表反转c实现

// ListReverse.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <malloc.h>
#include <iostream>
using namespace std;

typedef struct List
{
    struct List *next;
    int data;    
}*ListPtr;


void PrintList(ListPtr list)
{
    while(list!=NULL)
    {
        cout<<list->data<<"->";
        list = list->next;
    }
    cout<<endl;
}

ListPtr ReverseList(ListPtr list)
{
    if((list == NULL) || (list->next ==NULL))
    {
        return list;
    }

    ListPtr head = list;
    ListPtr headnext = head->next;
    ListPtr headnextnext = headnext->next;
    head->next = NULL;
    
    while(headnextnext != NULL)
    {
        headnext->next = head;
        head = headnext;
        headnext = headnextnext;
        headnextnext = headnextnext->next;    
    }
    headnext->next = head;
    return headnext;

}


int _tmain(int argc, _TCHAR* argv[])
{
    ListPtr head = (ListPtr)malloc(sizeof(List));
    ListPtr headtemp = head;
    int i=10;
    while(i--)
    {
        headtemp->data = i;
        headtemp = headtemp->next  =  (ListPtr)malloc(sizeof(List));

    }
    headtemp->data = i;
    headtemp->next = NULL;

    PrintList(head);    
    PrintList(ReverseList(head));
    


    return 0;
}

原文地址:https://www.cnblogs.com/harlanc/p/5162202.html