您的位置:首页 > 其它

LeetCode---(206)Reverse Linked List

2015-05-19 16:59 253 查看
Reverse a singly linked list.

输入一个链表的头结点,反转该链表并输出翻转后链表的头结点。

第一种:

/**
* 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==NULL)
return NULL;
ListNode *last=new ListNode(0);
last->next=head;

ListNode* p1=head;
head=last;
ListNode* first=p1;
ListNode* p2=p1->next;
ListNode* p3=NULL;
while(p2!=NULL)
{
p3=p2->next;
p2->next=p1;
p1=p2;
p2=p3;
}
last->next=p1;
first->next=NULL;
return head->next;

}
};

第二种:

class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* next = NULL;
while (cur != NULL) {
ListNode* next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}

return pre;
}
};

第三种:
/**
* 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 *newhead=NULL;
ListNode *pNode=head;
ListNode *pPrev=NULL;

while(pNode!=NULL)
{
ListNode *pNext=pNode->next;
if(pNext==NULL)
newhead=pNode;
pNode->next=pPrev;
pPrev=pNode;
pNode=pNext;
}
return newhead;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: