LeetCode 206 Reverse Linked List(链表操作)

来源:互联网 发布:郫都区人民政府 知乎 编辑:程序博客网 时间:2024/04/29 09:37

Reverse a singly linked list.

解题思路:注意几种特殊情况的处理。

代码如下:

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* reverseList(struct ListNode* head) {    //链表为空的情况    struct ListNode* last = head;    if(!last) return NULL;    //只有一个元素的情况    struct ListNode* now = last->next;    if(!now) return last;    //有两个元素的情况    struct ListNode* nxt = now->next;    if(!nxt){        now->next = last;        last->next = NULL;        return now;    }    //有三个及以上元素的情况    last->next = NULL;    while(now){        now->next = last;        last = now;        now = nxt;        if(nxt) nxt = nxt->next;    }    head = last;    return head;}

0 0
原创粉丝点击