題目:
方法一:創建新鏈表,遍歷舊鏈表,進行頭插
代碼實現:?
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/typedef struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head) {if(head==NULL){return head;}ListNode* newHead,*newTail;newHead=NULL;newTail=NULL;ListNode* pcur=head;ListNode* next=pcur->next;//注意這里要特殊討論空鏈表while(pcur){if(newHead==NULL){//鏈表為空時newHead=newTail=pcur;}else{//鏈表非空時next=pcur->next;//保存下一個節點pcur->next=newHead;newHead=pcur;}if(pcur!=NULL)pcur=next;}newTail->next=NULL;return newHead;
}
方法二:三指針法
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/typedef struct ListNode ListNode;
struct ListNode* reverseList(struct ListNode* head) {//方法二:三指針if(head==NULL){return head;}ListNode* n1=NULL;ListNode* n2=head;ListNode* n3=n2->next;while(n2){n2->next=n1;n1=n2;n2=n3;if(n2!=NULL)n3=n2->next;}return n1;
}
?