题目:反转链表
题目描述
输入一个链表,反转链表后,输出新链表的表头。
思路
①用栈
②循环,用pre、next记录前一个和下一个指针的位置
/*
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 *pre=NULL;
ListNode *next=NULL;
while(pHead){
next = pHead->next;
pHead->next = pre;
pre = pHead;
pHead = next;
}
return pre;
}
};