题目描述
输入一个链表,反转链表后,输出新链表的表头。
解题思路:
1.递归思想:
公式:
head=head.next;
head.next.next=head;
2.迭代:
思路分析:
(1)将iter指向头节点的下个节点:iter=head.next;
(2)将头节点的下个节点指向res:head.next=res;
(3)将res指向头节点,完成res往后移动:res=head;
(4)将head指向iter,即完成head的往后移动:head=iter;
实现代码:
/*publicclassListNode{intval;ListNodenext=null;ListNode(intval){this.val=val;}}*/publicclassSolution{publicListNodeReverseList(ListNodehead){returnReverseListByIterator(head);}/*递归解法*/publicListNodeReverseListByRecruit(ListNodehead){if(head==null
head.next==null){returnhead;}ListNoderes=ReverseList(head.next);head.next.next=head;head.next=null;returnres;}/*迭代解法思路分析:将iter指向头节点的下个节点:iter=head.next;将头节点的下个节点指向res:head.next=res;将res指向头节点,完成res往后移动:res=head;将head指向iter,即完成head的往后移动:head=iter;*/publicListNodeReverseListByIterator(ListNodehead){if(head==null
head.next==null){returnhead;}ListNoderes=null,iter=null;while(head!=null){iter=head.next;head.next=res;res=head;head=iter;}returnres;}}预览时标签不可点收录于话题#个上一篇下一篇