本文主要是介绍Day61.算法训练,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
206. 反转链表
/*** 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) {ListNode o1 = head;ListNode n1 = null;while (o1 != null) {ListNode temp = o1.next;o1.next = n1;n1 = o1;o1 = temp;}return n1;}
}
class Solution {public ListNode reverseList(ListNode head) {List o1 = new List(head);List o2 = new List(null);while (true) {ListNode listNode = o1.removeFirst();if (listNode == null) {break;}o2.addFirst(listNode);}return o2.head;}class List {private ListNode head;public List(ListNode head) {this.head = head;}public void addFirst(ListNode first) {first.next = head;head = first;}public ListNode removeFirst() {ListNode first = null;if (head != null) {first = this.head;this.head = this.head.next;}return first;}}
}
class Solution {public ListNode reverseList(ListNode head) {if (head == null || head.next == null) {return head;}ListNode listNode = reverseList(head.next);head.next.next = head;head.next = null;return listNode;}
}
class Solution {public ListNode reverseList(ListNode head) {if (head == null) {return null;}ListNode n1 = head;ListNode o1 = head;ListNode o2 = head.next;while (o2 != null) {o1.next = o2.next;o2.next = n1;n1 = o2;o2 = o1.next;}return n1;}
}
这篇关于Day61.算法训练的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!