面试题-链表反转c实现

xiaoxiao2025-11-27  7

// 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.6miu.com/read-5040084.html

最新回复(0)