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