剑指Offer 16 反转链表

来源:互联网 发布:tv007网络电视手机版 编辑:程序博客网 时间:2024/05/19 14:19

题目描述

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

思路

就某一个节点来说,我们要将他的next赋给前面的节点,那么原本后面的节点就不见了;所以我们将其保存起来啦

代码

static   public ListNode ReverseList(ListNode head) {          ListNode currentnode = head;          ListNode prev =null;          ListNode result=null;          while (currentnode!=null)          {              ListNode next = currentnode.next;              if (next ==null)                  result = currentnode;              currentnode.next=prev;              prev=currentnode;              currentnode=next;          }          return  result;        }

递归版
看题就想到了递归,但是递归写起来好难;

 public ListNode ReverseList(ListNode head) {     if (head==null||head.next==null)            //递归结束的条件              return head;          ListNode node = ReverseList(head.next);//遍历到最后一个节点          head.next.next=head;          head.next=null;          return node;                            //每次都返回node,只不过最后一次才管用        }}

收获

  1. 别看起来很简单的样子,我想想就知道该怎么办了,但是代码不会写啊;主要因为就是while循环的条件找错了;
  2. while条件尽量简单,节点尽可能一般化;
  3. 递归很帅的感觉,但是很难写;
0 0
原创粉丝点击