关闭

java头插法实现单链表逆置

615人阅读 评论(0) 收藏 举报
分类:

上周五去面试,面试官让写一个链表逆置,很简单的题目,自己是想用头插法解决,脑海里还总是存在着本地逆置的印象,结果我把自己绕晕,今天实现了一下,写在这里留个纪念吧。


package test;

class Node
{
	int data;
	Node nextNode;
}

public class testFour {
	public static Node reverse(Node head)
		{
			if(null == head || null == head.nextNode)
			{
				return head;
			}
			
			Node nextHead = new Node(); //待转置的链的下一个节点
			Node newHead = new Node(); //新链的头节点
			Node newn = new Node(); //新链里新插入的节点
			newHead = head;
			head = head.nextNode;
			newHead.nextNode = null; //新链的插入的第一个节点是尾节点
			while(head.nextNode != null)
			{
				nextHead = head.nextNode;
				newn = head;
				newn.nextNode = newHead;
				newHead = newn;
				head = nextHead;
			}
			newn = head;
			newn.nextNode = newHead;
			return newn;
		}
	
	public static void main(String[] args) {
		Node node = new Node();
		node.data = 1;
		Node nextnode = new Node();
		nextnode.data = 2;
		Node node3 = new Node();
		node3.data = 3;
		Node node4 = new Node();
		node4.data = 4;
		Node node5 = new Node();
		node5.data = 5;
		node.nextNode = nextnode;
		nextnode.nextNode = node3;
		node3.nextNode = node4;
		node4.nextNode = node5;
		node5.nextNode = null;
		
		Node newHead = new Node();
		newHead = reverse(node);
		while(newHead.nextNode != null)
		{
			System.out.println(newHead.data);
			newHead = newHead.nextNode;
		}
		System.out.println(newHead.data);
	}
}


0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:2511次
    • 积分:221
    • 等级:
    • 排名:千里之外
    • 原创:19篇
    • 转载:6篇
    • 译文:0篇
    • 评论:2条
    文章分类
    最新评论