【leetcode】206. Reverse Linked List

来源:互联网 发布:阿兹特克 知乎 编辑:程序博客网 时间:2024/06/05 16:05

题目要求:Reverse a singly 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;        }else{            ListNode pre = head;            ListNode p = head.next;            ListNode next = null;            while(p!=null)            {                //先用next存放下一个节点                next = p.next;                //再把当前结点的后继指向前一个节点                p.next = pre;                //再把pre和p往后移                pre = p;                p = next;            }            //最后清除头节点的环            head.next=null;            return pre;        }    }}


0 0
原创粉丝点击