##C++##逆置链表的升级版(k个节点的逆置)

逆置链表之前写过整条链表的逆置,今天在一本书上看到了关于k个节点的逆置。

关于k个节点的逆置有两个方法

方法一:利用栈来实现这个逆置,当进栈的个数达到了k个之后,就进行出栈操作,而当不足k个时,则直接连接在新链表的后面

方法二:记录链表的第一个位置,走k步之后记录尾节点,并记录尾节点的next,然后将尾节点的next置空,逆置这段新链表,以此类推  知道这段链表的结束。

代码实现如下:

//方法1:
Node* RotateList(Node* list, size_t k)
 {
	 assert(list);
	 if (list==NULL && k <2 )
	 {
		 return list;
	 }
	 Node* cur = list;
	 Node* newList = cur;
	 stack<int> s;
	 int count = 0;
	 while (cur)
	 {
			 s.push(cur->_data);
			 cur = cur->_next;
			 ++count;
		 if (count% k==0)
		 {		
			 while (newList != cur)
			 {
				 newList->_data = s.top();
				 s.pop();
				 newList = newList->_next;
			 }			
		 }
	 }
	 return list;
 }
 //方法2:
 Node* Reverse(Node *head){
	 Node *now, *next;
	 if (head == NULL)
		 return NULL;
	 now = head->_next;
	 head->_next = NULL;
	 while (now != NULL){
		 next = now->_next;
		 now->_next = head;
		 head = now;
		 now = next;
	 }
	 return head;
 }
 Node* RotateList2(Node* list, size_t k)
 {
	 assert(list);
	 if (list == NULL&&k < 2)
	 {
		 return list;
	 }
	 Node* cur = list;
	 Node* tmp = NULL;
	 Node* tail = NULL;
	 int count = 0;
	 while (cur)
	 {	
		 ++count;
		 if (count == k)
		 {
			 if (tail == NULL)
			 {
				 tmp = cur->_next;
				 cur->_next = NULL;
				 cur = tmp;
				 tmp = list;
				 list = Reverse(list);
				 tmp->_next = cur;
				 tail = tmp;
			 }
			 else
			 {
				 tmp = cur->_next;
				 cur->_next = NULL;
				 cur = tmp;
				 tmp = tail->_next;
				 tail->_next = Reverse(tmp);
				 tmp->_next = cur;
				 tail = tmp;
			 }
			 count = 0;
		 }
		 else
		 {
			 cur = cur->_next;
		 }
	 }
	 return list;
 }
 void test()
 {
	 Node* s1 = NULL;
	 PushBack(&s1, 1);
	 PushBack(&s1, 2);
	 PushBack(&s1, 3);
	 PushBack(&s1, 4);
	 PushBack(&s1, 5);
	 PushBack(&s1, 6);

	 PrintList(s1);
        Node* s = RotateList(s1,3);
      PrintList(s);
      Node* s = RotateList2(s1,3);
      PrintList(s);
 }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值