题解 | #链表内指定区间反转#

链表内指定区间反转

https://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c

#include <time.h>
int getVal(struct ListNode* head,int index)
 {
    struct ListNode* tmp=head;
    index -=1;
    while(index)
    {
        tmp=tmp->next;
        index--;
    }
    return tmp->val;
 }
 void setVal(struct ListNode* head,int index, int val)
 {
    struct ListNode* tmp=head;
    index -=1;
    while(index)
    {
        tmp=tmp->next;
        index--;
    }
    tmp->val=val;
 }
struct ListNode* reverseBetween(struct ListNode* head, int m, int n ) {
    // write code here
    int i,k1,k2;

    if(m>=n && m!=0)
    {
        return head;
    }
    for(i=0;i<((n-m+1)/2);i++)
    {
        k1=getVal(head, m+i);
        k2=getVal(head, n-i);
        setVal(head, n-i, k1);
        setVal(head, m+i, k2);
    }
    return head;
}

全部评论

相关推荐

小狗吃臭臭:以后用不到你设计的手机了,可惜!
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务