LintCode-剑指Offer-翻转链表

来源:互联网 发布:cf免费刷军衔软件 编辑:程序博客网 时间:2024/06/11 16:56
/**
 * 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
        if(head==NULL||head->next==NULL)
            return head;
        ListNode* r=new ListNode(0);
        ListNode* tmp=r;
        ListNode* tmp2=NULL;
        while(tmp!=NULL){
            tmp=head->next;
            head->next=r->next;
            r->next=head;
            head=tmp;
        }
        return r->next;
    }
};
0 0