Lintcode 翻转链表

翻转一个链表

样例

给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null

挑战 

在原地一次翻转完成

/**
 * 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 *temp1,*temp2;
        if(head==NULL)
        return NULL;
        if(head->next!=NULL){
        temp1=head->next;
        if(temp1->next!=NULL){
        temp2=temp1->next;
        temp1->next=head;
        head->next=NULL;
        head=temp1;
        temp1=temp2;
        
        }
        else{
             temp1->next=head;
             head->next=NULL;
             head=temp1;
             return head;
        }
        }
        else{
            return head;
        }
        while(temp1->next!=NULL){
        temp2=temp1->next;
        temp1->next=head;
        head=temp1;
        temp1=temp2;
        }
        temp1->next=head;
        head=temp1;
        return head;
    }
};



你可能感兴趣的:(LintCode编程)