剑指offer--算法题--16--递归循环两种方式反转链表

题目描述:

输入一个链表,反转链表后,输出链表的所有元素。
(hint : 请务必使用链表)

输入:

输入可能包含多个测试样例,输入以EOF结束。
对于每个测试案例,输入的第一行为一个整数n(0<=n<=1000):代表将要输入的链表的个数。
输入的第二行包含n个整数t(0<=t<=1000000):代表链表元素。

输出:

对应每个测试案例,
以此输出链表反转后的元素,如没有元素则输出NULL。

样例输入:
5
1 2 3 4 5
0
样例输出:
5 4 3 2 1

NULL

主要有两种方式 一种是循环 一种是递归

package jzoffer;

public class ReverseList {
	public static NewListNode ReverseList1(NewListNode head){
		NewListNode cur = head;
		NewListNode next = null;
		NewListNode pre = null;
		
		if(head == null || head.next == null){
			return head;
		}
		while(cur != null){
			next = cur.next;//保存下一个节点
			cur.next = pre;//当前节点指向前一个节点
			//第一次的话当前节点肯定就是头节点,头节点的指向肯定就是null了
			pre = cur;//前任节点到现任节点
			cur = next;//现任节点到下一节点
		}
		return pre;//直接返回最后一个输出就是了
	}
	
    public static NewListNode ReverseList2(NewListNode head){
		if(head == null || head.next == null){
			return head;//看懂了上面的非递归的话 我想这个递归实现
		}               //多在纸上画一画应该就可以实现了
		NewListNode secondElem = head.next; 
		head.next = null;
		NewListNode reverseRest = ReverseList2(secondElem);
		secondElem.next = head;
		head.next = null;
		return reverseRest;
	}
    public static void printList(NewListNode listNode){
		if(listNode == null){
			return;
		}
		if(listNode.next == null){
			System.out.println(listNode.data);
		}
		while(listNode != null){
			System.out.print(listNode.data+" ");
			listNode = listNode.next;
		
		}
	}
	public static void main(String[] args) {
		NewListNode head = new NewListNode();
		NewListNode second = new NewListNode();
		NewListNode third = new NewListNode();
		NewListNode forth = new NewListNode();
		NewListNode fifth = new NewListNode();
		NewListNode sixth = new NewListNode();//创建6个节点
		head.next = second;
		second.next = third;
		third.next = forth;
		forth.next = fifth;
		fifth.next = sixth;
		sixth.next = null;//将这6个节点按照顺序连接起来
		head.data = 1;
		second.data = 2;
		third.data = 3;
		forth.data = 4;
		fifth.data = 5;
		sixth.data = 6;//给他们填充数据
		NewListNode head2  = head;
		System.out.println("输出原本的链表");
		printList(head);
		System.out.println("");
		System.out.println("递归实现链表倒转");
		printList(ReverseList2(head));
//		System.out.println("");
//		System.out.println("非递归实现链表倒转");
//		printList(ReverseList1(head2));
		
	}
	public ReverseList() {
	}

}
class NewListNode{
	int data;
	NewListNode next;
}


猜你喜欢

转载自blog.csdn.net/lsm18829224913/article/details/80504280