【剑指offer】反转链表

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

*与之前的问题不同,这里需要修改链表的指向(之前的问题,不需要修改结点的指针,只需使用栈保存每个结点的值)

*注意非空处理以及最后一个结点指针的修改

 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         //非空处理
13         if(head==null) return null;
14        //记录待修改节点的前驱与后继
15         ListNode pre = null;
16         ListNode next = null;
17         
18         while(head.next!=null){
19            next = head.next;
20            head.next = pre;
21            pre = head;
22            head = next;
23         }
24    //将尾节点的前驱修改为倒数第二个节点
25         head.next = pre;
26         return head;
27     }
28 }
原文地址:https://www.cnblogs.com/singular/p/10033873.html