LeetCode 目录
Leetcode 54:螺旋矩阵Ⅰ
Leetcode 59:螺旋矩阵 Ⅱ
Leetcode 111: 二叉树的最小深度【递归/非递归求解/队列】
Leetcode 149:一条直线上最多的点数
LeetCode 150:计算逆波兰式(后缀表达式)的值
Leetcode 876:链表的中间节点
给定一个带有头结点 head 的非空单链表,返回链表的中间结点。
如果有两个中间结点,则返回第二个中间结点。
示例 1:
输入:[1,2,3,4,5]
输出:此列表中的结点 3 (序列化形式:[3,4,5])
返回的结点值为 3 。
示例 2:
输入:[1,2,3,4,5,6]
输出:此列表中的结点 4 (序列化形式:[4,5,6])
由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点
思路
统计链表总的节点个数cnt
返回中间的那个节点**(即cnt/2)**的ListNode
之前可能会一愣,为什么cnt为奇数偶数的时候都是返回cnt/2的那个值,按照例子跑一遍会发现结果是一样的
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
int cnt = 0;
ListNode* temp = head;
while(temp)
{
cnt++;
temp = temp -> next;
}
int flag = cnt/2;
ListNode* ans = head;
for(int i=0;i<flag;i++)
{
ans = ans->next;
}
return ans;
}
};