Java-------反转单链表

  
  问题描述: 给定一个单链表,将单链表进行反转。(即原单链表的头变为尾,尾变为头)
在这里插入图片描述
  算法思路:
  ①可以定义cur用来遍历链表,pre指向cur的前驱节点,curnext指向cur的后继节点,newhead代表链表新的头。
  ②当cur不为空时遍历,可以发现反转链表cur的next域就是原单链表的前驱节点地址,就是pre。所以将pre赋值给cur的指针域,pre等于cur,最后cur向后走一步。当cur的next为空时,此时cur就是反转之后链表的新的头结点。


  参考代码:

class ListNode{
    public int data;
    public ListNode next;

    public ListNode(int data){
        this.data=data;
        this.next=null;
    }
}//节点类


class MySignalList {
    public ListNode head;


    public MySignalList() {
        this.head = null;
    }


    //尾插法
    public void addLast(int data) {
        ListNode node = new ListNode(data);
        if (this.head == null) {
            this.head = node;
        } else {
            ListNode cur = head;
            while (cur.next != null) {
                cur = cur.next;
            }
            cur.next = node;
        }

    }

    //反转
    public  ListNode reverseList(){
        ListNode cur=this.head;
        ListNode newhead=null;
        ListNode pre=null;
        while(cur!=null){
            ListNode curnext=cur.next;
            if(curnext==null){
                newhead=cur;       //新的头节点
            }
            cur.next=pre;   //将前驱赋值给当前节点的next域
            pre=cur;
            cur=curnext;
        }
        return newhead;
    }

   //打印单链表
    public void display2(ListNode newHead){
        ListNode cur=newHead;
        while(cur!=null){
            System.out.print(cur.data+" ");
            cur=cur.next;
        }
        System.out.println();
    }
}




public class Test {
    public static void main(String[] args) {
        MySignalList mySignalList1 = new MySignalList();
        mySignalList1.addLast(1);
        mySignalList1.addLast(4);
        mySignalList1.addLast(6);
        mySignalList1.addLast(7);
        mySignalList1.addLast(56);
        ListNode cur= mySignalList1.reverseList();
        mySignalList1.display2(cur);
    }
}

//打印结果
56 7 6 4 1 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值