题目描述
输入一个链表,反转链表后,输出链表的所有元素。
思路
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
/*
* 思路:新建一个链表,把原链表的从头到尾遍历,一个个接到新链表的前面去
*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pReverse = NULL;
while(pHead != NULL){
ListNode* pNode = new ListNode(pHead->val);
pNode->next = pReverse;
pReverse = pNode;
pHead = pHead->next;
}
return pReverse;
}
};