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


前言

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


一、单链表是什么?

只能单向移动的链表

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;
	}

猜你喜欢

转载自blog.csdn.net/weixin_51422230/article/details/121527713