Reverse Linked List

本文介绍了一种反转链表的方法,并提供了一个Java实现示例。该方法通过迭代方式反转链表,利用三个指针进行节点之间的连接调整。文章还包含了一个用于验证反转功能正确性的简单示例程序。

https://leetcode.com/problems/reverse-linked-list/

Reverse a singly linked list

 1 public class Solution {
 2     public static ListNode reverseList(ListNode head) {
 3        if(head==null) return null;
 4        ListNode newHead=new ListNode(0);
 5        ListNode prehead=head.next;
 6        while(true){
 7        head.next=newHead.next;
 8        newHead.next=head;
 9        if(prehead==null) break;
10        head=prehead;
11        prehead=head.next;
12        }
13        return newHead.next;
14     }
15     public static class ListNode {
16     int val;
17     ListNode next;
18     ListNode(int x) {
19         val = x;
20     }
21     }
22     public static void main(String[]args){
23     ListNode[]node=new ListNode[4];
24     for(int i=0;i<node.length;i++){
25         node[i]=new ListNode(i);
26     }
27     node[0].next=node[1];
28     node[1].next=node[2];
29     node[2].next=node[3];
30     ListNode head=reverseList(node[0]);
31     while(head!=null){
32         System.out.println(head.val);
33         head=head.next;
34     }
35     }
36 }

 

转载于:https://www.cnblogs.com/qq1029579233/p/4480205.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值