1)解决方法一:采用头插法实现
struct ListNode* reverseList(struct ListNode* head){
//采用头插法来实现
struct ListNode* cur = head;
struct ListNode* newhead = NULL;
while(cur){
struct ListNode* next = cur->next;
cur->next = newhead;
newhead = cur;
cur = next;
}
return newhead;
}
思路:创建两个新指针cur与newhead,cur用来指向即将要头插的节点,而newhead指向头插新节点前链表的头节点,反复进行下列过程,直到cur为NULL:
1)保存尾插完当前节点cur后的节点:truct ListNode* next = cur->next;
2)将当前节点cur头插到newhead前:cur->next = newhead;
3)更新头节点:newhead = cur;
4)将1)中保存的节点赋值为下次要头插的节点:cur = next;
2)采用指针反转的方法来实现
struct ListNode* reverseList(struct ListNode* head){
//采用指针反转的方法来实现
struct ListNode* n1 = NULL;
struct ListNode* n2 = head;
//如果一开始就是空链表,则n2->next会产生空指针异常
if(n2 == NULL){
return NULL;
}
struct ListNode* n3 = head->next;
while(n2){
n2->next = n1;
n1 = n2;
n2 = n3;
//如果n3为NULL,则n3->next就会产生空指针异常
if(n3)
n3 = n3 -> next;
}
return n1;
}
思路:创建三个新指针n1、n2、n3,n2指向每次反转的节点,n1指向反转节点的前一节点,n3指向反转节点的后一节点,每次进行如下过程,直到n2为NULL:
1)将反转节点指向前一节点:n2->next = n1;
2)将n1,n2,n3分别后移一个节点。n1 = n2; n2 = n3;n3 = n3 -> next;
最后跳出循环时,n1指向旧链表的最后一个节点,也是新链表的头结点
故return n1即可