小言_互联网的博客

JAVA学习-单链表原地逆序

239人阅读  评论(0)

使用Java做题编写链表,尝试写了一个原地逆序函数

单链表内部节点只能下一个节点,无法指向上一个节点;
JAVA不能定义指针,引用相当于指针;
使用三个引用指向链表内部节点,依次向后游走;
代码如有错误、冗余或优化,感谢指点。

public class listReverse {
	public static void main(String[] args) {
		list l = new list();
		l.insert(1);
		l.insert(2);
		l.insert(3);
		l.show();
		l.reverse();
		l.show();
	}
	
}
class list{
	private class Node{
		private Object data;
		private Node next;
		public Node() {
			this.data = null;
			this.next = null;
		}
		
		public Node(Object data) {
			this.data = data;
			this.next = null;
		}

	}
	private Node temp;
	private Node head;
	public list() {
		head=new Node();
	}
	public void insert(Object o) {
		temp = head;
		Node n = new Node(o);
		while(temp.next!=null) {
			temp=temp.next;
		}
		temp.next=n;
	}
	public void show() {
		temp = head;
		while(temp.next!=null) {
			temp=temp.next;
			System.out.println(temp.data);
		}
	}
	//逆序函数
	public void reverse() {
		temp = head;
		Node temp1=temp.next;
		Node n;
		while(temp1!=null) {
			n=temp1;
			temp1=temp1.next;
			if(temp==head) {
				n.next = null;
			}
			else {
				n.next = temp;
			}
			temp = n;
		}
		head.next = temp;
	}

}

运行结果:


转载:https://blog.csdn.net/weixin_43288335/article/details/102490073
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场