c++翻转链表


#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <cstdlib>
#include <stack>
#include <queue>
#include <algorithm>
using  namespace std;
#define CLS(x,v)  memset(x,v,sizeof(x))
#define LL long long
#define M 50001


struct Node
{
    int data;
    Node *next;
};

Node* create(int n){
    if(n<1)return NULL;
     Node* p=new Node;// 返回类型是Node *
     p->data=1;
    Node *head=p;
    Node *temp;
    for(int i=2;i<=n;i++)
    {
        temp=new Node;
        temp->data=i;
        p->next=temp;
        p=temp;
    }
    p->next=NULL;
    return head;
}
//反转链表效率O(n)
Node* myreverse(Node* head)
{
    Node *one,*two,*three;
    //初始化第一 二个
    one=head;if(one==NULL)return NULL;//链表长度为0
    two=one->next;if(two==NULL)return one;//链表长度为1
    one->next=NULL;
    while(1)
    {
        //根据地第二个产生第三个
        three=two->next;
        two->next=one;
        if(three==NULL)break;
        //前移 第一、二个指针
        one=two;
        two=three;
    }
    return two;
}
//查看链表
void show(Node *p)
{
    while(p!=NULL)
    {
        printf("%d ",p->data);
        p=p->next;
    }
    printf("\n");
}
//释放链表
void myfree(Node *p){
    Node *temp;
    while(p!=NULL)
    {
        temp=p->next;
        delete p;
        p=temp;
    }
}
int main()
{
    Node* head=create(5);
    show(head);
    //
    head=myreverse(head);
    show(head);
    //
    myfree(head);
    return 0;
}


题目描述: 给定一个链表,每k个节点为一组进行翻转。例如,给定链表1->2->3->4->5,k=2,则应返回2->1->4->3->5。请注意,你需要在不修改链表节点值的情况下完成此操作。 示例: 输入: 1->2->3->4->5, k = 2 输出: 2->1->4->3->5 思路: 这道题是链表的操作,我们可以用递归来实现,每次递归处理k个节点,翻转它们,返回翻转后的头节点,然后将它接到上一组的尾部。 具体实现: 首先,我们需要定义一个辅助函数reverse,用来翻转链表。它的实现方法是,用三个指针pre、cur、next来遍历链表,将cur的next指向pre,然后将三个指针往后移动一个节点,重复这个过程,直到遍历完整个链表。 接下来,我们可以定义一个递归函数,它的参数是链表头节点和k。如果链表的长度小于k,说明不需要翻转,直接返回头节点;否则,我们先翻转前k个节点,然后将它们的尾节点接到下一组翻转后的头节点,递归处理下一组节点。每次递归返回的是翻转后的头节点,最后将所有头节点连接起来即可。 代码实现: /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* reverse(ListNode* head) { ListNode* pre = NULL; ListNode* cur = head; while (cur != NULL) { ListNode* next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; } ListNode* reverseKGroup(ListNode* head, int k) { ListNode* cur = head; int cnt = 0; while (cur != NULL && cnt != k) { // 找到第k+1个节点 cur = cur->next; cnt++; } if (cnt == k) { // 如果找到了,就翻转前k个节点 cur = reverseKGroup(cur, k); // 递归处理下一组节点 while (cnt-- > 0) { // 将翻转后的头节点接到下一组节点的尾部 ListNode* next = head->next; head->next = cur; cur = head; head = next; } head = cur; } return head; } };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值