LeetCode Swap Nodes in Pairs

本文介绍了一种链表中节点两两交换的算法实现,并通过示例展示了如何创建链表及进行节点交换的过程。该算法适用于需要调整链表中元素顺序的场景。
ListNode *swapPairs(ListNode *head) {
	ListNode *head2=NULL,*p=NULL,*q=NULL,*s=NULL;
	p = head;
	if (p==NULL||p->next==NULL)
		return p;
	while(p!=NULL&&p->next!=NULL)
	{
		s = p->next;
		p->next = s->next;
		p = p->next;
		if (head2==NULL)
		{
			head2 = s;
			q = head2;
		}
		else
		{
			q->next = s;
			q = q->next;
		}
	}
	if (q!=NULL)
		q->next = NULL;

	ListNode *head3=NULL;
	s = head3;
	while(head!=NULL&&head2!=NULL)
	{
		p = head2;
		q = head;
		head = head->next;
		head2 = head2->next;
		if(head3==NULL)
		{
			head3 = p;
			head3->next = q;
			s = head3->next;
		}
		else
		{
			s->next = p;
			p->next = q;
			s = q;
		}
	}
	if (head==NULL)
		s->next = head2;
	if(head2==NULL)
		s->next = head;
	return head3;
}
ListNode *l1 = new ListNode(1);
	ListNode *l2 = new ListNode(2);
	ListNode *l3 = new ListNode(3);
	ListNode *l4 = new ListNode(4);
	ListNode *l5 = new ListNode(5);
	ListNode *l6 = new ListNode(6);
	ListNode *l7 = new ListNode(7);
	ListNode *l8 = new ListNode(8);
	ListNode *l9 = new ListNode(9);
	l1->next = l2;
	l2->next = l3;
	l3->next = l4;
	l4->next = l5;
	l5->next = l6;
	l6->next = l7;
	l7->next = l8;
	l8->next = l9;
	ListNode *head3=NULL;
	head3 = swapPairs(l1);
	ListNode *h=head3;
	while(h!=NULL)
	{
		cout<<h->val<<" ";
		h = h->next;
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值