题目:反转单链表。
思路:我们分别建立三个指针,其中指针pre保持已反转链表的头指针(注意是已反转的,用途是当下将cur指针链接到它),cur指针代表当前正在遍历的指针,next记录cur的下一个指针,否则链表断开,无法找到其在原链表中的下一位置。这样不断循环,直至cur为NULL,注意返回的指针为pre,而不是NULL,因为此时cur已经为空,pre为我们所需要的头结点。
/*
struct ListNode {int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* pre=NULL;
ListNode* cur=pHead;
ListNode* next=NULL;
while(cur!=NULL){
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};