代码改变世界

反转链表

2019-01-26 23:21  YihangZhou  阅读(95)  评论(0编辑  收藏  举报

题目描述

输入一个链表,反转链表后,输出新链表的表头。
 
 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         if(head==null)return null;
13         ListNode cur = head;
14         ListNode pre = null;
15         ListNode temp = null;
16         while(cur.next!=null){
17             pre=cur;
18             cur=cur.next;
19             pre.next=temp;
20             temp=pre;
21         }
22         cur.next=pre;
23         return cur;
24     }
25 }