链表-Reverse Linked List

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* reverseList(struct ListNode* head) {
    if(!head||!head->next)
        return head;
    struct ListNode *cur=head;
    struct ListNode *tail=head;
    while(tail->next)
        tail=tail->next;
    while(cur!=tail)
    {
        head=cur->next;
        cur->next=tail->next;
        tail->next=cur;
        cur=head;
    }
    return head;
}

有一个问题,leetcode给出的链表测试数据应该是不包含头结点,所以写代码的时候需要注意一下。

还有另外一种解法,就是把所有指针的方向反过来,代码如下。

struct ListNode* reverseList(struct ListNode* head) {
    if(head&&head->next)
    {
        struct ListNode* pre=NULL;
        struct ListNode* cur=head;
        struct ListNode* pnext=cur->next;
        
        while(pnext)
        {
            cur->next=pre;
            pre=cur;
            cur=pnext;
            pnext=cur->next;
        }
        cur->next=pre;
        head=cur;
    }
    return head;
}

 

posted on 2016-03-08 14:48  summerkiki  阅读(161)  评论(0编辑  收藏  举报