反转链表前N个节点

反转链表前N个节点,并返回反转后的链表

ListNode结构如下

    public class ListNode {
        int val;
        ListNode next;
        ListNode(int x) { val = x; }
    }
class Solution {
    //后继节点
    ListNode successor = null;
    public ListNode reverseN(ListNode head, int n){
        if (head == null || head.next == null) return head;
        if (n == 1){
            successor = head.next;
            return head;
        }
        ListNode last = reverseN(head.next, n-1);
        head.next.next = head;
        head.next = successor;
        return last;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是一个反转链表的C程序: ```c #include <stdio.h> #include <stdlib.h> typedef struct ListNode { int val; struct ListNode *next; } ListNode; ListNode* reverseList(ListNode* head) { ListNode *prev = NULL, *curr = head, *next = NULL; while (curr != NULL) { next = curr->next; curr->next = prev; prev = curr; curr = next; } return prev; } void printList(ListNode* head) { while (head != NULL) { printf("%d ", head->val); head = head->next; } printf("\n"); } int main() { ListNode *head = (ListNode*)malloc(sizeof(ListNode)); head->val = 1; head->next = (ListNode*)malloc(sizeof(ListNode)); head->next->val = 2; head->next->next = (ListNode*)malloc(sizeof(ListNode)); head->next->next->val = 3; head->next->next->next = NULL; printf("Original list: "); printList(head); head = reverseList(head); printf("Reversed list: "); printList(head); return 0; } ``` 在这个程序中,我们定义了一个链表节点结构体`ListNode`,并定义了一个函数`reverseList`,它接受一个链表头结点指针作为参数,并返回反转后的链表头结点指针。我们还定义了一个函数`printList`,它接受一个链表头结点指针作为参数,并打印出链表中所有节点的值。 在`reverseList`函数中,我们定义了三个指针变量`prev`、`curr`和`next`,用来保存当节点一个节点和后一个节点。我们使用一个while循环遍历整个链表,每次将当节点的下一个节点保存到`next`指针中,然后将当节点的`next`指向一个节点,最后将`prev`指针指向当节点,`curr`指针指向`next`节点。当遍历完成后,`prev`指向的就是反转后的链表头结点,我们将它返回即可。 在`main`函数中,我们创建了一个包含三个节点的链表,并打印出原始链表和反转后的链表。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值