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; } }