Java:需要了解LinkNode的构造函数和支持函数



我已经开始研究Java中的LinkedList问题。我遇到了让我困惑的LinkNode。我在leetcode找到了下面的问题解决方案:https://leetcode.com/problems/odd-even-linked-list/discuss/78079/Simple-O(N( 时间O(1(空间Java解决方案。我想了解更多关于LinkNode的信息。此外,执行以下功能需要什么样的支持功能?

public class Solution {
public ListNode oddEvenList(ListNode head) {
if (head != null) {

ListNode odd = head, even = head.next, evenHead = even; 

while (even != null && even.next != null) {
odd.next = odd.next.next; 
even.next = even.next.next; 
odd = odd.next;
even = even.next;
}
odd.next = evenHead; 
}
return head;
}}

LeetCode已经在他们的模板中定义了它,你不必编码:

/**
* 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 oddEvenList(ListNode head) {

}
}

你的代码很好,它会通过:

class Solution {
public ListNode oddEvenList(ListNode head) {
if (head != null) {
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even;
while (even != null && even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
}
return head;
}
}

例如,如果您想在本地进行测试,可以创建一个名为b.java:的文件

import java.util.*;
import javafx.util.*;
class Solution {
public ListNode oddEvenList(ListNode head) {
if (head != null) {
ListNode odd = head;
ListNode even = head.next;
ListNode evenHead = even;
while (even != null && even.next != null) {
odd.next = odd.next.next;
even.next = even.next.next;
odd = odd.next;
even = even.next;
}
odd.next = evenHead;
}
return head;
}
}

class b {
public static void main(String[] args) {
Solution object = new Solution();
System.out.println(object);
}
}

class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

然后写你的代码,不管你想测试它

相关内容

  • 没有找到相关文章

最新更新