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 三少_爷 阅读(98) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


<2012年8月>
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

导航

统计

常用链接

留言簿

随笔分类

随笔档案

My Website

搜索

最新评论

阅读排行榜

评论排行榜