面试题-----单链表的反转

#include <iostream>
using namespace std;

struct node{
    int value;
    struct node *next;
};

struct node *head;

void insert(struct node * &head,int value)
{
    if(head == NULL)
    {
        head = new struct node;
        head->value = value;
        head->next = NULL;
        return;
    }

    struct node *p = new struct node;
    p->value = value;
    p->next = NULL;

    struct node *q = head;
    while(q->next != NULL)
    {
        q = q->next;
    }

    q->next = p;

}

void print(struct node *head)
{
    struct node *p = head;
    while(p != NULL)
    {
        cout<<p->value<<"  ";
        p = p->next;
    }
}
void reverse(struct node * &head)
{

    if(head == NULL || head->next == NULL)
        return;
    struct node *p = head;
    struct node *q = head->next;

    while(q != NULL)
    {
        struct node *next = q->next;
        q->next = p;
        p = q;
        q = next;
    }
    head->next = NULL;
    head = p;
}

int main()
{
    head = NULL;

    insert(head,1);
    insert(head,3);
    insert(head,5);
    insert(head,9);
    insert(head,11);
    insert(head,16);
    insert(head,18);
    insert(head,6);
    insert(head,10);
    insert(head,12);
    insert(head,13);
    insert(head,15);
    cout<<"链表:";
    print(head);
    cout<<endl<<"逆序后为:"<<endl;
    reverse(head);
    print(head);
    cout<<endl;

    return 0;
}

 还可以使用递归实现

//递归实现
struct node *reverse2(struct node *head)
{
    if(head == NULL || head->next == NULL)
        return head;

    struct node *p;
    struct node *next = head->next;
    p = reverse2(next);
    next->next = head;
    head->next = NULL;
    return p;
}

 

posted @ 2017-11-13 11:07  青儿哥哥  阅读(300)  评论(0编辑  收藏  举报