温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C语言数据结构旋转链表的实现

发布时间:2020-10-12 15:53:24 来源:脚本之家 阅读:151 作者:lqh 栏目:编程语言

C语言数据结构旋转链表的实现

实例:

给出链表1->2->3->4->5->null和k=2

返回4->5->1->2->3->null

分析

感觉很直观,直接把分割点找出来就行,记得k可能大于len,要取模

代码:

/** 
 * Definition for singly-linked list. 
 * struct ListNode { 
 *   int val; 
 *   ListNode *next; 
 *   ListNode(int x) : val(x), next(NULL) {} 
 * }; 
 */ 
class Solution { 
public: 
  /** 
   * @param head: the list 
   * @param k: rotate to the right k places 
   * @return: the list after rotation 
   */ 
  ListNode *rotateRight(ListNode *head, int k) { 
    // write your code here 
    if(head==NULL) 
      return head; 
    int len = 0; 
    ListNode*temp = head; 
    while(temp) 
    { 
      len++; 
      temp = temp->next; 
    } 
    k%=len; 
    if(k==0) 
      return head; 
    k = len-k; 
    temp = head; 
    while(k>1) 
    { 
      temp = temp->next; 
      k--; 
    } 
    ListNode*newStart = temp->next; 
    temp->next = NULL; 
    temp = newStart; 
    while(temp->next) 
      temp = temp->next; 
    temp->next = head; 
    return newStart; 
  } 
}; 

 以上就是C语言数据结构旋转链表的实现,如有疑问请留言或者到本站社区交流讨论,本站关于数据结构的文章还有很多,希望大家搜索查阅,大家共同进步!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI