reverse singly linked list

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <iostream>
using namespace std;

typedef struct Node
{
    int data;
    Node * next;
}Node,*list;

void createList(Node * &head)
{
    if(head == NULL)
    {
        head = (Node *)malloc(sizeof(Node));
        head->data = 1;
        head->next = NULL;
    }

    Node * p = head;
    while(p->next != NULL)
    {
        p = p->next;
    }
    for(int j = 2; j < 10; j++)
    {

        Node * q = (Node *)malloc(sizeof(Node));
        q->data = j;
        q->next = NULL;

        p->next = q;
        p = q;
    }
}
Node * reverse(Node * head)
{
    Node * p,*q,*r;
    if(head == NULL)
        return NULL;
    if(head->next == NULL)
        return head;
    p = head;
    q = head->next;
    while(q)
    {
        r = q->next;
        q->next = p;
        p = q;
        q = r;
    }
    head->next = NULL;
    return p;
}
int main()
{    
    Node * head = NULL;
    createList(head);
    Node * p = head;
    while(p)
    {
        printf("%d  ",p->data);
        p = p->next;
    }
    printf("\n");
    p = reverse(head);
    while(p)
    {
        printf("%d  ",p->data);
        p = p->next;
    }
    printf("\n");
    system("pause");
    return 1;
}

posted on 2012-08-20 09:45 三少_爷 阅读(117) 评论(0)  编辑 收藏 引用

<2025年6月>
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345

导航

统计

常用链接

留言簿

随笔分类

随笔档案

My Website

搜索

最新评论

阅读排行榜

评论排行榜