链表反转

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL

数据初始化:

   public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }

        @Override
        public String toString() {
            return String.valueOf(val);
        }
    }


        ListNode listNode = new ListNode(5);
        ListNode listNode1 = new ListNode(4);
        ListNode listNode2 = new ListNode(3);
        ListNode listNode3 = new ListNode(2);
        ListNode listNode4 = new ListNode(1);

        listNode4.next = listNode3;
        listNode3.next = listNode2;
        listNode2.next = listNode1;
        listNode1.next = listNode;

 

方法一: 

public ListNode reverseList(ListNode head) {

        if(head==null){
            return null;
        }

        ListNode remember = head ;
        ListNode curr = head ;

        //第一次遍历 主要是记录看看要建立的数组  有多少个元素
        int lengthNum = 0 ;
        while (curr!=null){
            curr = curr.next;
            lengthNum++ ;
        }

        curr = remember ;
        //创建一个固定大小的数组  并且从0 开始 顺序存放listnode
        ListNode[] nodearray = new ListNode[lengthNum] ;
        lengthNum = 0 ;
        while (curr!=null){
            nodearray[lengthNum] = curr;
            curr = curr.next;
            lengthNum++ ;
        }

        //逆序遍历 数组  把后一个元素的next  设置位 前一个元素
        for(int i = nodearray.length-1;i>=0;i--){
            if(i==0){
                nodearray[i].next = null;
            }else {
                nodearray[i].next = nodearray[i-1];
            }
        }
        //返回数组的最后一个元素  (这也是反转后的第一个元素 )
        return nodearray[nodearray.length-1];
    }

 

方法二:  

public ListNode reverseList(ListNode head) {

        ListNode pre = null ;
        while(head!=null){
            //记录下  下一个node  否则直接赋予相反方向的 node    next引用就丢失了
            ListNode next = head.next;
            //反转操作
            head.next = pre;
            //移动pre 指针   因为遍历到下一个元素的话  当前元素 就是 “上个元素了”
            pre = head;
            //移动head 指针
            head = next;                    
        }

        return pre;
    }

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值