一招教你解决单链表逆序【Java&C】

对于给定的单链表,我们如何将链表逆置,最理想的状态是原地逆转,接下来我们来分析一下算法,并给出Javac两种解法,仅供参考!!!

分析算法

在这里插入图片描述
在这里插入图片描述

我们来看代码实现

C

#include<stdio.h>
#include<stdlib.h>
typedef struct LNode {
	int data;
	struct Node* next;
}LNode;

LNode* InitList(LNode* L, int n) {
	int i = 0;
	L = (LNode*)malloc(sizeof(LNode));
	L->next = NULL;
	LNode* tail = L;
	while (i < n) {
		LNode* newNode = (LNode*)malloc(sizeof(LNode));
		int temp;
		scanf("%d", &temp);
		newNode->data = temp;
		/*newNode->next = L->next;
		L->next = newNode;*/
		tail->next = newNode;
		tail = newNode;
		i++;
	}
	tail->next = NULL;
	return L;
}

void print1(LNode* L) {
	LNode* cur = L;
	while (cur->next) {
		cur = cur->next;
		printf("%d ", cur->data);
	}
	
}
void print2(LNode* L) {
	LNode* cur = L;
	while (cur->next) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
}

LNode* reverse(LNode* L) {
	LNode* pre = NULL;
	LNode* next = NULL;
	while (L!=NULL) {
		next = L->next;
		L->next = pre;
		pre = L;
		L = next;
	}
	return pre;
}


int main() {
	int n;
	scanf("%d", &n);
	LNode* L = (LNode*)malloc(sizeof(LNode));
	L=InitList(L, n);
	print1(L);
	printf("\n");
	L = reverse(L);
	print2(L);
	return 0;
}

Java

public class demo01 {
    public static class Node{
        public int value;
        public Node next;
        public Node(int data){
            value=data;
        }
    }

    public static Node reverseLinkedList(Node head){//逆序链表
        Node next=null;
        Node pre=null;
        while(head!=null){
            next=head.next;
            head.next=pre;
            pre=head;
            head=next;
        }
        return pre;
    }

    public static void printList(Node head){
        if(head==null)
            return;
        Node cur=head;
        while(cur!=null){
            System.out.print(cur.value+" ");
            cur=cur.next;
        }
    }

    public static void main(String[] args) {
        Node n1=new Node(1);
        n1.next=new Node(2);
        n1.next.next=new Node(3);
        n1=reverseLinkedList(n1);
        printList(n1);
    }
}


大家好好看看图解,如果觉得有用的话,不妨点个免费的关注哦,我们继续加油!

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值