【LeetCode】Swap Nodes in Pairs & Reverse Nodes in k-Group

本文深入探讨了链表中关键的节点操作问题,包括两节点互换位置和按组反转链表。通过具体实例演示了解决这些问题的高效算法,并强调了使用常量空间的重要性。

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

链表题是一个难点,需要多写多练习



Swap Nodes in Pairs

 

Given a linked list, swap every two adjacent nodes and return its head.

For example,
Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.


class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        if(head == NULL || head->next == NULL)	return head;
        //printList(head,"head");	
        //至少两个结点 
		ListNode *p = head, *prep = NULL;
        ListNode *q = p->next;
        p->next = q->next;
		q->next = p;
		head = q;
		prep = p;
		p = p->next;
		//printList(head,"head");	
		while(p != NULL && p->next != NULL)
		{
			q = p->next;
			p->next = q->next;
			q->next = p;
			prep->next = q;
			prep = p;
			p = p->next;
			//printList(head,"head");	
		}
		return head; 
    }
};



Reverse Nodes in k-Group

  Total Accepted: 7206  Total Submissions: 29535 My Submissions

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,
Given this linked list: 1->2->3->4->5

For k = 2, you should return: 2->1->4->3->5

For k = 3, you should return: 3->2->1->4->5


class Solution {
public:
    ListNode *reverseKGroup(ListNode *head, int k) {
        if(head == NULL || head->next == NULL || k == 1) return head;
        int i = 0;        
        ListNode *tmphead = head, *tmptail = head, *tmpSaveHead = NULL,*tmpSaveTail = NULL , *p;
        
        while(tmptail != NULL)
        {
	        while(++i<k && tmptail != NULL)
	        	tmptail = tmptail->next;
	       	if(tmptail == NULL) return head;	       	
	       	tmpSaveTail = tmptail->next;
	       	//printList(tmphead,"tmphead");
	       	p = tmphead->next;
	       	tmptail = tmphead;
	       	while(i-- > 1)
	       	{
	       		tmptail->next = p->next;
				p->next = tmphead;
				tmphead = p;
				p = tmptail->next;	
	   		}
	       	
	       	if(tmpSaveHead)	tmpSaveHead->next = tmphead;
	       	else	head = tmphead;
	       	tmpSaveHead = tmptail;
	       	//printList(tmphead,"1tmphead");
	       	//system("pause");
	       	//printList(head,"head");
	       	//system("pause");
	       	tmphead  = tmpSaveTail;
	       	tmptail = tmpSaveTail;
	       	i = 0;
        }     
		return head;
    }
};




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值