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;
}

猜你喜欢

转载自blog.csdn.net/qq_38251616/article/details/105414128