思路一:
可以从头开始遍历链表,每遍历一个节点,用头插法将该节点插入新的链表中。
这个思路适合翻转整个链表,缺点是需要新建一个哨兵结点。
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* hair = new ListNode(0);
ListNode* p = head;
ListNode* pre = hair;
while(p!=NULL){
ListNode* tmp = p->next;
p->next = pre->next;
pre->next = p;
p = tmp;
}
ListNode* ret = hair->next;
delete hair; hair = NULL;
return ret;
}
};
思路二:
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* p = head;
while(p!=NULL){
ListNode* nex = p->next;
p->next = prev;
prev = p;
p = nex;
}
return prev;
}
};