LintCode-35.翻转链表
翻转链表
翻转一个链表
样例
给出一个链表 1->2->3->null ,这个翻转后的链表为 3->2->1->null
挑战
在原地一次翻转完成
标签
链表 优步 脸书
code
/**
* Definition of ListNode
*
* class ListNode {
* public:
* int val;
* ListNode *next;
*
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
// write your code here
ListNode *l1=NULL,*l2=NULL,*l3=NULL;
l1 = head;
// 链表没有节点或有一个节点
if(l1 == NULL || l1->next == NULL) {
return l1;
}
l2 = l1->next;
// 链表有2节点
if(l2->next == NULL) {
l2->next = l1;
l1->next = NULL;
return l2;
}
l3 = l2->next;
// 链表有3个以上节点
if(l2->next != NULL) {
while(l2 != l3) {
l2->next = l1;
if(l1 == head)
l1->next = NULL;
l1 = l2;
l2 = l3;
if(l3->next != NULL)
l3 = l3->next;
}
l2->next = l1;
return l2;
}
}
};