题目:
方法一:创建新链表,遍历旧链表,进行头插
代码实现:
/*** 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;
}