反转链表,之前在PTA做过的,写完之后发现出现段错误,检查一下发现是第一个头节点没有把next 指针置NULL,加上之后就通过了。
另外要注意结构体定义的构造函数,默认是NULL,而不是null,所以判断链表是不是到最后,要和NULL比较而不是null。
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) :
* val(x), next(NULL) {
* }
* };
*/
class Solution {
public:
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> ReverseList;
if(head == NULL) return ReverseList;
struct ListNode *preNode,*curNode,*curTemp,*newHead;
preNode = head;
curNode = head->next;
curTemp = head->next;
head->next = NULL; //容易漏掉
while(curNode != NULL){
curTemp = curNode->next;
curNode->next = preNode;
preNode = curNode;
curNode = curTemp;
}
newHead = preNode;
struct ListNode *Rear=newHead;
while(Rear != NULL){
ReverseList.push_back( Rear->val );
Rear = Rear->next;
}
return ReverseList;
}
};