13.【链表】Reverse Linked List--Accepted code

来源:互联网 发布:淘宝打印电子面单流程 编辑:程序博客网 时间:2024/06/07 00:22

leetcode url:https://leetcode.com/problems/reverse-linked-list/

/** * 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 p1=head;        ListNode p2=p1.next;        head.next=null;//很重要,否则会形成循环链表        while(p1!=null && p2!=null){            ListNode t=p2.next;            p2.next=p1;            p1=p2;            p2=t;        }        return p1;    }}
0 0
原创粉丝点击