方法一:创建一个新的链表,其头结点newhead一开始为NULL,遍历旧的链表,遍历过程中若结点不为NULL,则将其头插到新链表中。每头插一次,newhead就更新一次。
struct ListNode* reverseList(struct ListNode* head)
{
struct ListNode* cur=head;
struct ListNode* newhead=NULL;//newhead单纯存储新链表的头结点地址,置空是为了第一个头插时,尾结点指向NULL。
while(cur)
{
struct ListNode* tmp=cur->next;//记录下一个结点地址,以防找不到。
cur->next=newhead;//头插
newhead=cur;//更新newhead
cur=tmp;//检查旧链表下一个结点
}
return newhead;
}