15 反转链表

题目描述

输入一个链表,反转链表后,输出链表的所有元素。


方法1:
利用循环:
pre head next
1→2→3

 

 1 /*
 2 public class ListNode {
 3     int val;
 4     ListNode next = null;
 5 
 6     ListNode(int val) {
 7         this.val = val;
 8     }
 9 }*/
10 public class Solution {
11     public ListNode ReverseList(ListNode head) {
12         if(head==null||head.next==null) return head;
13         ListNode pre = head;
14         head = head.next;
15        _*** pre***__***.next=null;***_
16         while(head!=null){
17             ListNode next= head.next;
18             head.next=pre;
19             pre = head;
20             head = next;
21         }
22         return pre;
23     }
24 }

 

递归版:


抽象出来

1→2->3

R(2)表示2节点以后的都已经反转好了,而且返回的是反转后的头结点3
1->2←3



我们要做的就是 把 1——>2反转成1<——2
1——————>2
pre head

pre.next = null;
head.next = pre;

需要注意把pre.next 置为null

 

 

 

 1 public class Solution {
 2     public ListNode ReverseList(ListNode head) {
 3         if(head==null||head.next==null) return head;
 4         ListNode pre = head;
 5         head = head.next;
 6         ListNode rhead= ReverseList(head);
 7         _***pre***__***.next = null;***_
 8         head.next = pre;  
 9         return  rhead;
10     }
11 }

 

转载于:https://www.cnblogs.com/zle1992/p/8029770.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值