天天看點

LeetCode題組:第206題-反轉連結清單

1.題目

難度:

簡單

反轉一個單連結清單。

示例:

輸入: 1->2->3->4->5->NULL

輸出: 5->4->3->2->1->NULL

2.我的解答

/**
 * 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 *p=head;
    struct ListNode* q=head->next;
    struct ListNode* r=head->next->next;
    p->next=NULL;
    while(q){
        q->next=p;
        p=q;
        q=r;
        if(r) r=r->next;
    }
    head=p;
    return head;
}           

複制