剑指Offer第八题:反转链表

题目描述

输入一个链表,反转链表后,输出新链表的表头。

题目分析

反转链表将整个链表倒置过来,我们只需要将节点的next指向的方向由下一个改成指向上一个就完成了。

算法分析

  • 如果给的链表为null,那么我们直接返回空。
  • 如果不为空进行置换操作

源代码

 1 public class ListNode {
 2     int val;
 3     ListNode next = null;
 4 
 5     ListNode(int val) {
 6         this.val = val;
 7     }
 8 }
 9 public class Solution {
10     public ListNode ReverseList(ListNode head) {
11         if(head==null)
12             return null;
13         ListNode curr=head;
14         ListNode newNode=null;
15         ListNode temp=null;
16         ListNode pre=null;
17         
18         while(curr!=null) {
19             temp=curr.next;
20             curr.next=pre;
21             if(temp==null)
22                 newNode=curr;
23             pre=curr;
24             curr=temp;
25         }
26         return newNode;
27     }
28 }

 

posted @ 2018-09-03 17:33  轻抚丶两袖风尘  阅读(83)  评论(0编辑  收藏  举报