法一:反转指针
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head){ if(head==NULL) return NULL; struct ListNode*n1=NULL; struct ListNode*n2=head; struct ListNode*n3=n2->next; while(n2) { n2->next=n1; n1=n2; n2=n3; if(n3) n3=n3->next; } return n1; }
法二:头插法
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */ struct ListNode* reverseList(struct ListNode* head){ if(head==NULL) return NULL; struct ListNode*cur=head; struct ListNode*newnode=NULL; struct ListNode*next=cur->next; while(cur) { cur->next=newnode; newnode=cur; cur=next; if(next) next=next->next; } return newnode; }