反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。

代码

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* ReverseList(ListNode* pHead) {
        if (pHead == NULL || pHead->next == NULL) {
            return pHead;
        }
        
		ListNode* prev = pHead, *head = pHead->next, *cur = head->next;
        
        head->next = prev;
        prev->next = NULL;
        
        while (cur != NULL) {
            prev = cur;
            cur = cur->next;
            
            prev->next = head;
            head = prev;
        }
        return head;
    }
};
原文地址:https://www.cnblogs.com/jecyhw/p/6536417.html