反转链表

反转链表

  

  题目描述

    输入一个链表,反转链表后,输出新链表的表头。
 
 
   思路:目的是要将链表反转,但是单链表只有后节点,没有前节点。我可以手动创建一个辅助的前节点来帮助反转链表。
    
 1     public ListNode ReverseList(ListNode head) {
 2         if(head==null||head.next==null) return head;
 3         //辅助的前节点
 4         ListNode pre = null;
 5         //用来记录当前节点的后节点
 6         ListNode next = null;
 7         while(head!=null){
 8             //先将后节点信息保存下来
 9             next = head.next;
10             //将现节点的后节点反转
11             head.next = pre;
12             //迭代变换现节点和前节点
13             pre = head;
14             head = next;
15         }
16         //当最终现节点为null时,终止循环,此时的前节点,正是新链表的表头。
17         return pre;
18     }

 

 

posted @ 2018-07-04 12:09  张天气Up  阅读(88)  评论(0编辑  收藏  举报