LeetCode Rotate List

本文详细介绍了如何使用C++编程语言实现旋转链表的功能,包括定义链表节点、计算链表长度、进行旋转操作并输出旋转后的链表元素。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

要说这题没什么新鲜玩意,我确实第一次没提交过,不是什么大难题,考虑不周到,马虎之类,人生有多少时候我们是跌倒在这里呢?

// LeetCode_RotateList.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <iostream>
using namespace std;

struct ListNode {
	    int val;
	    ListNode *next;
	    ListNode(int x) : val(x), next(NULL) {}
	};

ListNode *rotateRight(ListNode *head, int k) {
	if (head==NULL||k==0)
		return head;
	ListNode *q=head,*p=head;
	ListNode *newhead = head;
	int len = 0;
	while(newhead!=NULL)
	{
		newhead=newhead->next;
		len++;
	}
	if(k%len==0)
		return head;
	if(k>len)
		k = k%len;
	while(k>0&&q->next!=NULL)
	{
		q = q->next;
		k--;
	}
	while(q->next!=NULL)
	{
		q = q->next;
		p = p->next;
	}
	newhead = p->next;
	p->next = NULL;
	q->next = head;
	return newhead;
}

int _tmain(int argc, _TCHAR* argv[])
{
	ListNode *a = new ListNode(1);
	ListNode *b = new ListNode(2);
	ListNode *c = new ListNode(3);
	ListNode *d = new ListNode(4);
	ListNode *e = new ListNode(5);
	a->next = b;
	b->next = c;
	c->next = d;
	d->next = e;
	ListNode *newhead = rotateRight(a,2);
	ListNode *p = newhead;
	while(p!=NULL)
	{
		cout<<p->val<<" ";
		p = p->next;
	}
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值