【Leetcode】Reverse LinkedList

来源:互联网 发布:峰途网络 编辑:程序博客网 时间:2024/06/06 09:24

太经典的题目了,我就不废话了,只是为了po这个我非常obsessed的方法:

/** * Definition for singly-linked list. * public class ListNode { *     int val; *     ListNode next; *     ListNode(int x) { val = x; } * } */public class Solution {    public ListNode reverseList(ListNode head) {        if(head==null||head.next==null)            return head;                ListNode second = head.next;        head.next=null;                ListNode rest = reverseList(second);        second.next = head;                return rest;    }}


public ListNode reverseList(ListNode head) {    if(head==null || head.next == null)         return head;     ListNode p1 = head;    ListNode p2 = head.next;     head.next = null;    while(p1!= null && p2!= null){        ListNode t = p2.next;        p2.next = p1;        p1 = p2;        if (t!=null){            p2 = t;        }else{            break;        }    }     return p2;}

0 0