链表:链表的基本结构,实现单链表的反转

直接上代码(主要思想都在注释里面,就是需要三个类似指针(java又没有指针这一说,可以当作指针理解),一个个往后遍历,最后当前的节点为空时证明到尾部了)

public class singleLL {
    public static void main(String[] args) {
        ListNode head = new ListNode();
        ListNode tail = head;
        for (int i = 0; i < 10; i++) {
            ListNode cur = new ListNode(i);
            tail.next = cur;
            tail = cur;
        }
        ListNode h = head.next;
        while(h != null) {
            System.out.print(h.val + " ");
            h = h.next;
        }
        System.out.println();
        head = head.next;
        ListNode newHead = Solution.reverse(head);
        h = newHead;
        while(h != null) {
            System.out.print(h.val + " ");
            h = h.next;
        }
    }
    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
        ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    }
    public static class Solution{
        public static ListNode reverse(ListNode head){
            ListNode pre = null; //存放当前节点的前一个节点
            ListNode cur = head;//存放当前节点
            ListNode next;//存放当前节点的后一个节点,防止当前节点指向自己的前一个节点时,后一个节点丢失
            while(cur != null){
                next = cur.next;//next保存当前节点的后一个节点
                cur.next = pre; //实现链表反转,指向自己的前一个节点
                pre = cur; //当前节点完成反转后,pre和cur都往后走一个位置
                cur = next;
            }
            return pre;
        }
    }
}

 运行结果:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值