其他分享
首页 > 其他分享> > 反转链表

反转链表

作者:互联网

反转链表:迭代和递归

经典题,记录一下

public class LinkedListReverse {
	public static void main(String[] args) {
		LinkedList test = new LinkedList();
		for(int i = 0; i < 10; i++)
			test.add(new java.util.Random().nextInt(30));
		System.out.println(test.toString(test.first));
		Nod y = reverse1(test.first);
		System.out.println(test.toString(y));
		System.out.println(test.toString(reverse2(y)));
	}
	public static Nod reverse1(Nod x) {
		Nod first = x;
		Nod reverse = null;
		while(first != null) {
			Nod second = first.next;
			first.next = reverse;
			reverse = first;
			first = second;
		}
		return reverse;
	}
	public static Nod reverse2(Nod x) {
		Nod first = x;
		if(first == null) return null;
		if(first.next == null) return first;
		Nod second = first.next;
		Nod rest = reverse2(second);
		second.next = first;
		first.next = null;
		return rest;
	}
}
class Nod{
	public int val;
	public Nod next;
	Nod(){
		val = 0;
		next = null;
	}
}
class LinkedList{
	Nod first;
	int length;
	LinkedList(){
		first = null;
		length = 0;
	}
	public void add(int val) {
		Nod oldfirst = first;
		first = new Nod();
		first.val = val;
		if(length == 0)
			length++;
		else {
			first.next = oldfirst;
			length++;
		}
	}
	public String toString(Nod head) {
		Nod temp = head;
		String s = "";
		while(temp != null) {
			s += temp.val + "->";
			temp = temp.next;
		}
		if(!s.equals(""))
			s = s.substring(0, s.length() - 2);
		return s;
	}
}

标签:Nod,反转,next,链表,test,null,public,first
来源: https://blog.csdn.net/qq_40622253/article/details/97156973