链表反转

如1->2->3->4->5,反转输出5->4->3->2->1
发现对地址这一块不是太熟悉。

//节点结构
class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 }

解法1:新建空间

   public ListNode rerere(ListNode head){
        ListNode pre=null;
        ListNode first = null;
        while (head!=null){
            first=new ListNode(head.val);
            if(pre!=null) first.next=pre;
            pre=first;
            head=head.next;
        }
        return first;
        //然后遍历输出first即可得到反转的链表
    }

解法2:在原地址上操作

写了一个,乱的跟麻一样。地址都混了

假设存在链表1→2→3→∅,我们想要把它改成 ∅←1←2←3。

在遍历列表时,将当前节点的 next指针改为指向前一个元素。由于节点没有引用其上一个节点,因此必须事先存储其前一个元素。在更改引用之前,还需要另一个指针来存储下一个节点。不要忘记在最后返回新的头引用!

class Solution {
    public ListNode reverseList(ListNode head) {
        ListNode cur=head,pre=null;
        while(cur!=null){
            ListNode next=cur.next;
            cur.next=pre;
            pre=cur;
            cur=next;
        }
        return pre;
    }
}
class Solution {
    public ListNode reverseList(ListNode head) {
      if(head==null||head.next==null) return head;
      ListNode p=reverseList(head.next);
      head.next.next=head;
      head.next=null;
      return p;
    }
}

如 1 2 3 4 5.
递归回来的时候,p=5
head=4,那么head.next.next就是5.next=4.
然后head.next=4.next=null,组成了 5 4 null
然后再回去的时候,p=4
head=3,head.next.next=head就是4.next=3
然后head.next=3.next=null,组成了5 4 3 null.
///

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值