struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
单向链表,第一个结点规定为头结点
反转原理图示
步骤1: 把旧链表头保存到nowNode里面
步骤2: 删除旧链表第一个元素,也就是pHead指针指向第二个元素,pHead=pHead->next ;
步骤3: 将nowNode添加到newHead前面,也就是这个结点指向原来的newHead,再把newHead赋值为nowNode
(步骤二与步骤三可以调换)
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode* newHead=NULL;
ListNode* nowNode;
while(pHead!=NULL){
nowNode=pHead; //把待添加结点先保存下来
pHead=pHead->next;//删除原链表第一个结点
nowNode->next=newHead;//把nowNode加到newHead前面
newHead=nowNode;
}
return newHead;
}
};