题目:输入一个链表,反转链表后,输出新链表的表头。

  • 代码如下
 1 public class Demo3 {
 2 
 3     public static void main(String[] args) {
 4         // 先创建多个节点,供测试使用
 5         ListNode listNode1 = new ListNode(1);
 6         ListNode listNode2 = new ListNode(2);
 7         ListNode listNode3 = new ListNode(3);
 8         ListNode listNode4 = new ListNode(4);
 9         ListNode listNode5 = new ListNode(5);
10         // 把各个节点链起来
11         listNode1.next = listNode2;
12         listNode2.next = listNode3;
13         listNode3.next = listNode4;
14         listNode4.next = listNode5;
15         listNode5.next = null;
16 
17         System.out.println("原始链表中的数据如下:");
18         printList(listNode1);
19         
20         System.out.println("\n\n反转之后的链表:");
21         ListNode reverseList = reverseList(listNode1);
22         printList(reverseList);
23     }
24 
25     public static ListNode reverseList(ListNode head) {
26         // 如果当前链表为null,则直接返回null
27         if (head == null)
28             return null;
29         ListNode next;
30         ListNode pre = null;
31         while (head != null) {
32             next = head.next;
33             head.next = pre;
34             pre = head;
35             head = next;
36         }
37         return pre;
38     }
39     
40     /**
41      * 遍历单链表
42      * @param listNode
43      */
44     public static void printList(ListNode listNode) {
45         ListNode tempNode = listNode;
46         while(tempNode != null){
47             System.out.printf("%d\t",tempNode.val);
48             tempNode = tempNode.next;
49         }
50     }
51 }
1 public class ListNode {
2     int val;
3     ListNode next = null;
4 
5     public ListNode(int val) {
6         this.val = val;
7     }
8 }
  • 运行截图

 4-输入一个链表,反转链表后,输出新链表的表头 算法

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄