【面试题16】反转链表

题目:

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


分析:

反转链表只需改变链接方向,改变方向时需要将原本指向后一个结点的链接方向指向前一个结点,因此需要记录下三个结点。


实现:(非递归)

  1. public ListNode ReverseList(ListNode head) {  
  2.     ListNode cur = head;  
  3.     ListNode next = null;  
  4.     ListNode pre = null;  
  5.     if (head == null || head.next == null) {  
  6.         return head;  
  7.     }  
  8.     while (cur != null) {  
  9.         next = cur.next;  
  10.         // 改变链方向  
  11.         cur.next = pre;  
  12.         // 移动结点,继续操作  
  13.         pre = cur;  
  14.         cur = next;  
  15.     }  
  16.     return pre;  
  17. }  

public class Solution {
     public ListNode ReverseList(ListNode head) {
       
         if (head== null )
             return null ;
         //head为当前节点,如果当前节点为空的话,那就什么也不做,直接返回null;
         ListNode pre = null ;
         ListNode next = null ;
         //当前节点是head,pre为当前节点的前一节点,next为当前节点的下一节点
         //需要pre和next的目的是让当前节点从pre->head->next1->next2变成pre<-head next1->next2
         //即pre让节点可以反转所指方向,但反转之后如果不用next节点保存next1节点的话,此单链表就此断开了
         //所以需要用到pre和next两个节点
         //1->2->3->4->5
         //1<-2<-3 4->5
         while (head!= null ){
             //做循环,如果当前节点不为空的话,始终执行此循环,此循环的目的就是让当前节点从指向next到指向pre
             //如此就可以做到反转链表的效果
             //先用next保存head的下一个节点的信息,保证单链表不会因为失去head节点的原next节点而就此断裂
             next = head.next;
             //保存完next,就可以让head从指向next变成指向pre了,代码如下
             head.next = pre;
             //head指向pre后,就继续依次反转下一个节点
             //让pre,head,next依次向后移动一个节点,继续下一次的指针反转
             pre = head;
             head = next;
         }
         //如果head为null的时候,pre就为最后一个节点了,但是链表已经反转完毕,pre就是反转后链表的第一个节点
         //直接输出pre就是我们想要得到的反转后的链表
         return pre;
     }
}

实现:递归:

  1. public ListNode Reverse(ListNode head) {  
  2.     if (head == null || head.next == null) {  
  3.         return head;  
  4.     }  
  5.     ListNode secondElem = head.next;  
  6.     head.next = null;  
  7.     ListNode reverseRest = Reverse(secondElem);  
  8.     secondElem.next = head;  
  9.     return reverseRest;  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值