做网站记什么科目,成都百度小程序开发,备案域名注册,利用百度图片做网站外链Reverse a singly linked list. Solution 1: 思路#xff1a;null的使用。用一个null node来承接#xff0c;一个一个接上去即可。一刷的时候还觉得这node转化好麻烦好神奇#xff0c;熟悉之后其实做起来很快。 /*** Definition for singly-linked list.* public class List…Reverse a singly linked list. Solution 1: 思路null的使用。用一个null node来承接一个一个接上去即可。一刷的时候还觉得这node转化好麻烦好神奇熟悉之后其实做起来很快。 /*** 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(headnull){return head;}ListNode lastnull;while(head!null){ListNode copyhead.next;head.nextlast;lasthead;headcopy;}return last;}
} Solution 2: follow up : Use Recursion 思路如果head.next不是null递归head.next注意先把head.next指针存好方便于reverse之后接上head。因为返回的是一个listnode用一个dummy node来把node用于输出。如果head.next是null的话直接返回head即可。Recursion真的是一个神器 /*** 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(headnull){return head;}ListNode dummynew ListNode(-1);if(head.next!null){ListNode copyhead.next;dummy.nextreverseList(head.next);copy.nexthead;head.nextnull;}else{return head;}return dummy.next;}
} 转载于:https://www.cnblogs.com/Machelsky/p/5858680.html