程序员面试题100题第19题——反转链表

1 、链表相邻元素翻转

2 、题目:输入一个链表的头结点,反转该链表,返回反转后链表的头结点;

LNode* ReverseLinkList(LNode* head)//带头结点
{
    if(head == NULL)//注意
        return head;

    LNode* p=head->next;
    LNode* temp=NULL;
    LNode* trail=NULL;

    while(p != NULL)
    {   //4句
        temp=p;
        p=p->next;
        temp->next=trail;
        trail=temp;
    }
    head->next=trail;
    return head;
}

3 、题目:输入一个链表的头指针,反转该链表,返回反转后链表的头指针;

LNode* ReverseLinkList(LNode* head)//不带头结点
{
    LNode* temp=NULL;
    LNode* trail=NULL;

    while(head != NULL)
    {   //4句
        temp=head;
        head=head->next;
        temp->next=trail;
        trail=temp;
    }
    head=trail;
    return head;
}
posted @ 2012-10-01 21:40  logzh  阅读(228)  评论(0编辑  收藏  举报