您的位置:首页 > 其它

LeetCode 206. Reverse Linked List

2016-10-29 11:05 260 查看

描述

反转链表

解决

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head)
return NULL;
ListNode* tHead = head;
while (head -> next)
{
ListNode* tmp = head -> next;
head -> next = tmp ? tmp -> next : NULL;
if (tmp)
{
tmp -> next = tHead;
tHead = tmp;
}

}
return tHead;
}
};


/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tHead = NULL;
while (head)
{
ListNode *tmp = head;
head = head -> next;
tmp -> next = tHead;
tHead = tmp;
}
return tHead;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode