翻转链表

/**
 * Definition of ListNode
 * 
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 * 
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */


class Solution
{
public:
	/*
	* @param head: n
	* @return: The new head of reversed linked list.
	*/
	ListNode * reverse(ListNode * head)
	{
		// write your code here
		if(head==NULL)
		{
		    return NULL;
		}
		ListNode * p1 = NULL;
		ListNode *p2 = head->next;
		while (p2!=NULL)
		{
            head->next=p1;
            p1=head;
            head=p2;
            p2=p2->next;
		}
        head->next=p1;
        return head;
	}
};

你可能感兴趣的:(翻转链表)