链表反转

package leetcode.list;

/**
 * @基本功能:反转链表
 * @program:summary
 * @author:peicc
 * @create:2019-08-17 12:00:59
 **/
public class ListReverse {
    public static void main(String[] args) {
        LinkList myLinkList=new LinkList();
        for (int i = 0; i <10 ; i++) {
            myLinkList.add(i);
        }
        System.out.println("原链表元素为:");
        myLinkList.print(myLinkList.head);
        System.out.println("递归反转后:");
        LinkList.ListNode newHead=reverseList(myLinkList.head);
        myLinkList.print(newHead);
        System.out.println("遍历翻转后:");
        LinkList.ListNode newHead1=reverseListByTraverse(newHead);
        myLinkList.print(newHead1);

    }
    //反转链表:递归
    public static LinkList.ListNode reverseList(LinkList.ListNode head){
        if(head==null||head.next==null){
            return head;
        }
        LinkList.ListNode next=head.next;
        LinkList.ListNode temp=reverseList(next);
        next.next=head;
        head.next=null;
        return temp;

    }
    //反转链表:遍历
    public static LinkList.ListNode reverseListByTraverse(LinkList.ListNode head){
        if(head==null||head.next==null){
            return head;
        }
        LinkList.ListNode current=head;
        LinkList.ListNode next=null;
        LinkList.ListNode newHead=null;
        while(current!=null){
            next=current.next;
            current.next=newHead;//将当前结点保存为头结点,所以其后继元素为之前的头结点
            newHead=current;//将当前结点设为头结点
            current=next;
        }
        return newHead;
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值