0%

【链表】单向链表的反转

三指针法遍历,一次遍历则完成反转:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
ListNode* ReverseList(ListNode* pHead) {
//no node
if(pHead==nullptr) return pHead;
ListNode* pre=nullptr,*mid=pHead,*last=nullptr;
//more node/single node
while(mid->next!=nullptr){
//confirm the location
last=mid->next;
mid->next=pre; pre=mid;mid=last;
}
mid->next=pre;
pHead=mid;
return pHead;
}