206_反转链表

给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。

Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseList(ListNode head) {
        if(head==null || head.next==null){
            return head;
        }
        return process(head);

    }

    private ListNode process(ListNode head){
        ListNode cur=head;
        ListNode p=null;
        while(cur!=null){
            //保存下一个节点
            ListNode next=cur.next;
            cur.next=p;
            p=cur;
            cur=next; 
        }

        return p;

    }
}

  

 

posted @ 2021-08-28 11:32  sherry001  阅读(28)  评论(0编辑  收藏  举报