作者:lksxq_468 | 来源:互联网 | 2023-09-17 17:59
说明 算法:Minimum Path Sum LeetCode地址:https://leetcode.com/problems/reverse-linked-list/
题目: Reverse a singly linked list.
Example:
Input: 1-> 2-> 3-> 4-> 5-> NULL Output: 5-> 4-> 3-> 2-> 1-> NULL Follow up:A linked list can be reversed either iteratively or recursively. Could you implement both?
解题思路 链表反转,实现方式有顺序遍历,还有递归。注意启动头脑系统二进行慢思考验证。
代码 – ListNode 改良后的ListNode可以接受整型数组为参数,构建一个链表。 toString()
打印链表格式数据:
1--> 2--> 3--> 4--> 5--> Null
ListNode
public class ListNode { public int val; public ListNode next; public ListNode ( int x) { val = x; } static public ListNode listNodeWithIntArray ( int [ ] input) { ListNode head = new ListNode ( 0 ) ; ListNode node = head; for ( int i: input) { ListNode newNode = new ListNode ( i) ; node. next = newNode; node = node. next; } return head. next; } @Override public String toString ( ) { StringBuilder sb = new StringBuilder ( ) ; ListNode node = this ; while ( node != null) { sb. append ( node. val) . append ( "-->" ) ; node = node. next; } return sb. append ( "Null" ) . toString ( ) ; } }
代码 – 遍历1 遍历的方法,每次都创建一个新的节点,这样交换,不会受到原有链表的干扰。缺陷是head在最后,指向了最后一个节点。
public ListNode reverseList ( ListNode head) { ListNode current = null; ListNode previous = null; while ( head != null) { previous = current; current = new ListNode ( head. val) ; current. next = previous; head = head. next; } return current; }
代码 – 遍历2 这种遍历方法,因为直接对current的遍历,原有head不受影响。 注意:
先保存next节点,再做顺序交换。 最后返回的是previous节点,因为在循环的最后都把current赋值给previous。 public ListNode reverseListWithoutChangeHead ( ListNode head) { ListNode current = head; ListNode previous = null; ListNode nextNode; while ( current != null) { nextNode = current. next; current. next = previous; previous = current; current = nextNode; } return previous; }
代码 – 递归 递归方法的技巧在于,head为当前节点,head.next.next = head;
, 同时记得把head.next = null;
, 递归到最后,返回最后一个节点。
public ListNode reverseListWithRecursive ( ListNode head) { while ( head == null || head. next == null) { return head; } ListNode p = reverseListWithRecursive ( head. next) ; head. next. next = head; head. next = null; return p; }
测试方法 public static void main ( String[ ] args) { int [ ] input = { 1 , 2 , 3 , 4 , 5 } ; ListNode head = ListNode. listNodeWithIntArray ( input) ; System. out. println ( "Input: " + head. toString ( ) ) ; ReverseLinkedList obj = new ReverseLinkedList ( ) ; ListNode result = obj. reverseListWithRecursive ( head) ; System. out. println ( "Output: " + result. toString ( ) ) ; }
运行结果
Input: 1--> 2--> 3--> 4--> 5--> Null Output: 5--> 4--> 3--> 2--> 1--> Null
总结 链表反转,容易出错,不信请试试。
代码下载: https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/common/ListNode.java https://github.com/zgpeace/awesome-java-leetcode/blob/master/code/LeetCode/src/popular/ReverseLinkedList.java