描述
翻转一个链表
您在真实的面试中是否遇到过这个题?
是
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
挑战
在原地一次翻转完成
1.可以选择 不改变链表结构 直接改变数据即可。
/** * Definition of singly-linked-list: * * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: n * @return: The new head of reversed linked list. */ ListNode * reverse(ListNode * head) { // write your code here if(head==NULL){ return NULL; } stack<int> stk; ListNode *cur=head; while(cur!=NULL){ stk.push(cur->val); cur=cur->next; } cur=head; while(cur!=NULL){ cur->val=stk.top(); cur=cur->next; stk.pop(); } return head; } };
2.上一个方法是个取巧的办法,可以通过申请三个指针来完成
/** * Definition of singly-linked-list: * * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ class Solution { public: /** * @param head: n * @return: The new head of reversed linked list. */ ListNode * reverse(ListNode * head) { // write your code here if(head==NULL){ return NULL; } ListNode *p1=head; ListNode *p2=head->next; ListNode *p3; p1->next=NULL; while(p2!=NULL){ p3=p2->next; p2->next=p1; p1=p2; p2=p3; } head=p1; return head; } };