您的位置:首页 > 编程语言 > Java开发

java实现单链表反转(遍历方式)

2015-11-23 15:36 519 查看
千辛万苦啊!!

public class NodeDemo {

public static void main(String[] args)
{

Node head = new Node(0);
Node temp = null;
Node cur = null;
for(int i=1;i<10;i++)
{
temp = new Node(i);
if(i==1)
head.setNextNode(temp);
else
cur.setNextNode(temp);
cur = temp;
}
Node h = head;
while(h!=null)
{
System.out.print(h.getData()+",");
h = h.getNextNode();
}
head = reverse(head);
System.out.println("");
while(head!=null)
{
System.out.print(head.getData()+",");
head = head.getNextNode();
}
}

public static Node reverse(Node node)
{
Node pre = node;
Node cur = node.getNextNode();
Node next;
while(cur!=null)
{
next = cur.getNextNode();
cur.setNextNode(pre);
pre = cur;
cur = next;
}
node.setNextNode(null);
return pre;
}

}

class Node
{
int data;
Node next;
Node(int data)
{
this.data = data;
this.next = null;
}
public void setNextNode(Node node)
{
this.next = node;
}
public Node getNextNode()
{
return next;
}
public int getData()
{
return data;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: