已给定的listNode的代码块:
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; }
}
我的解题思路:
数出listnode的长度,然后除以2,再将之后的节点值即节点赋给新的listnode。
class Solution {
public ListNode middleNode(ListNode head) {
int cnt = 1;
ListNode temp = head;
while(temp.next != null){
temp = temp.next;
cnt++;
}
ListNode ans = null;
for(int i = 0 ; i < cnt / 2 ; i++){
head = head.next;
}
ans = new ListNode(head.val,head.next);
return ans;
}
}
三版答案:
第一版:
利用题目信息,定义一个listnode类型的数组,数组中每个元素的head依次向后移
最后返回1/2处的数组元素。
class Solution {
public ListNode middleNode(ListNode head) {
ListNode[] A = new ListNode[100];
int t = 0;
while (head != null) {
A[t++] = head;
head = head.next;
}
return A[t / 2];
}
}
第二版:
和我的思路挺像的,只不过是不停的移动头节点,不是赋值罢了。
class Solution {
public ListNode middleNode(ListNode head) {
int n = 0;
ListNode cur = head;
while (cur != null) {
++n;
cur = cur.next;
}
int k = 0;
cur = head;
while (k < n / 2) {
++k;
cur = cur.next;
}
return cur;
}
}
第三版:
一次走两个节点,有意思!
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}