链表逆置

面试的同学经常提起在面试时经常有被问到关于链表逆置的问题,今晚有时间也就写了一个,在下面程序中有创建链表和逆置两个功能,具体代码如下:

#include <iostream>
using namespace std;

typedef char node_type;
typedef struct node
{
       node_type data;
       struct node *next;
}node_list, *_node_list;

_node_list createList(char data[], int size)
{
     _node_list head,my_node;
     head = new node_list;
     head->next = NULL;
     my_node = head;
    // cout<<size<<endl;
     for(int i=0; i<size; i++)
     {
             my_node = (_node_list)malloc(sizeof(node_list));
             my_node->data = data[i];
             my_node->next = head->next;
             head->next = my_node;
     }
     return head;
}

void output(_node_list node)
{
     while(node)
     {
         cout<<node->data<<"->";
         node = node->next;
     }
}

void reverse(_node_list node)
{
     _node_list head = node;
      node = node->next->next;
      _node_list temp,temp1;
      temp1 = head->next;
      temp1->next = NULL;
     while(node)
     {    
          temp = node->next;
          node->next = head->next;
          head->next = node;
          node = temp;
     }
     output(head);
}

int main(void)
{
    char data[] = {'a','b','c','d','e'};
    int size = sizeof(data)/sizeof(data[0]);
    //reverse(node);;
    _node_list node = createList(data,size);
    reverse(node);
    return 1;
}

posted @ 2012-08-07 22:31  SA高处不胜寒  阅读(180)  评论(0编辑  收藏  举报