单链表,双向链表和他们的反转


前言

简单的说一下两种表的结构,和他们的反转方法


一、单链表是什么?

只能单向移动的链表

1.定义节点

	public static class Node {
		public int value;//值
		public Node next;//指向下一个的引用

		public Node(int data) {//构造函数
			this.value = data;
		}
	}

2.遍历


	public static void printLinkedList(Node head) {
		System.out.print("Linked List: ");
		while (head != null) {
			System.out.print(head.value + " ");
			head = head.next;
		}
		System.out.println();
	}

3.反转

	public static Node reverseList(Node head) {//返回反转之后的头节点
		Node pre = null;//这个引用是用来指向反转过程中的头部
		Node next = null;//这个指针一直指向原链表,不断在第一个和第二个之间动
		while (head != null) {
			next = head.next;//将next放到第二个节点
			head.next = pre;//将原链表的第一个节点联想反转后的链表的尾节点
			pre = head;//使它往后移一个,一直指向尾部
			head = next;//回到原链表
		}
		return pre;
	}

二、双向链表是什么

1.定义节点

public static class DoubleNode {
		public int value;
		public DoubleNode last;//区别就是两个指针了
		public DoubleNode next;

		public DoubleNode(int data) {
			this.value = data;
		}
	}

2.遍历

//区别就是从左到右,从右到左遍历了两次
public static void printDoubleLinkedList(DoubleNode head) {
		System.out.print("Double Linked List: ");
		DoubleNode end = null;
		while (head != null) {
			System.out.print(head.value + " ");
			end = head;
			head = head.next;
		}
		System.out.print("| ");
		while (end != null) {
			System.out.print(end.value + " ");
			end = end.last;
		}
		System.out.println();
	}

3.反转

	public static DoubleNode reverseList(DoubleNode head) {
		DoubleNode pre = null;
		DoubleNode next = null;
		//基本过程和单链表一样,只不过每次多了一个执政换
		while (head != null) {
			next = head.next;
			head.next = pre;
			head.last = next;
			pre = head;
			head = next;
		}
		return pre;
	}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

醉卧考场君莫笑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值