Leetcode刷题指南-链表的中间结点(1609)

1)题目

链表两数相乘

要求:

输出链表的中间结点,给定一个带有头节点head的非空单链表,返回链表的中间节点。

如果有两个中间节点,则返回第二个中间节

样例

Example 1:

Input: 1->2->3->4->5->null
Output: 3->4->5->null
Example 2:

Input: 1->2->3->4->5->6->null
Output: 4->5->6->null

2)思路

分两种情况,链表长度len为偶数,判断当节点等于(1 + len) / 2,输出链表,当链表长度len为奇数,判断当节点等于1 + len/ 2,输出节点

3)代码

两种方法:
//头文件
#pragma once
#include "pch.h"
#include <iostream>
using namespace std;

#include <vector>
class ListNode
{
public:
	int val;
	ListNode *next;
};

class ListNode;
class Solution {
public:
	/**
	 * @param head: the head node
	 * @return: the middle node
	 */
	ListNode * middleNode(ListNode * head)
	{
		ListNode *p = head;
		int len = 0;
		while (p != NULL)
		{
			p = p->next;
			len++;
		}



		if (len % 2 != 0)
		{
			int len1 = 1;
			int a = (1 + len) / 2;
			ListNode *q = head;
			while (q != NULL)
			{
				q = q->next;
				len1++;
				if (len1 == a)
				{
					return q;
				}
			}
		}
		else
		{
			int len2 = 1;
			int b = 1 + len / 2;
			ListNode *m = head;
			while (m != NULL)
			{
				m = m->next;
				len2++;
				if (len2 == b)
				{
					return m;
				}
			}

		}
	};
	ListNode *vector2lianbiao(vector<int> nums)
	{
		ListNode *head, *p, *rear;
		head = rear = new class ListNode;
		head->val = nums[0];
		rear->next = NULL;

		for (int i = 1; i < nums.size(); i++)
		{
			p = new class ListNode;
			p->val = nums[i];
			rear->next = p;
			rear = p;

		}
		rear->next = NULL;
		return head;
	};

	void print_lianbiao(ListNode *head)
	{
		ListNode *p = head;
		while (p != NULL)
		{
			cout << p->val;
			cout << endl;
			p = p->next;
		}
		cout << endl;
	};
};



//主函数
#include "pch.h"
#include <iostream>
using namespace std;

#include "1609.h"


class Solution;
Solution function;
int main()
{
	int count;
	ListNode *result, *result1;
	vector<int> nums2 = { 1,2,3,4,5,6};
	result = function.vector2lianbiao(nums2);
	result1=function.middleNode(result);
	function.print_lianbiao(result1);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值