当前位置: 代码迷 >> 综合 >> Java数据结构和算法(六)—算法—反转链表
  详细解决方案

Java数据结构和算法(六)—算法—反转链表

热度:56   发布时间:2024-02-26 22:51:30.0

数组的话跟排好队的学生一样,第一个假如从0开始报数。让他们记住自己的数字,那叫到哪个数字就能找到对应的学生了。
而链表的话像是没有排好队的学生,但是关系是连接在一起的。每个人持有一张卡片,卡片上写了他指向谁。

结构比较简单。

public class ListNode {int val;ListNode next;ListNode(int x) {val = x;}
}

 

 

1 递归方式:

public class Solution {private static int i = 0;public static ListNode reverseList(ListNode head) {if(head == null || head.next == null){return head;}ListNode reverseNode = reverseList(head.next);head.next.next = head;head.next = null;return reverseNode;}public static void main(String[] args) {ListNode node1 = new ListNode(1);ListNode node2 = new ListNode(2);ListNode node3 = new ListNode(3);// ListNode node4 = new Li