题目:
链表操作,单链表就地逆置
解题思路:
很经典的一个链表算法题..其实需要注意的就是在改变链表的时候一定要维持你需要的指针的相对位置...
其实挺简单的...
public class Q24 {
public static void main(String[] args) {
//建立链表
Node head = new Node(1);
Node before = head;
Node now = null;
for(int i = 2;i<10;i++)
{
now = new Node(i);
before.next = now;
before = now;
}
now = head;
while(now!=null)
{
System.out.println(now.element);
now = now.next;
}
//链表就地逆置
head = Reverse(head);
while(head!=null)
{
System.out.println(head.element);
head = head.next;
}
}
public static Node Reverse(Node head)
{
if(head == null)
{
System.out.println("ERROR");
return null;
}
Node p = null;
Node q = null;
Node r = head;
while(r != null) //关键代码..就是必须要全部指针都到了预期的位置再改变指针指向........Notice
{
p = q;
q = r;
r = r.next;
if(q != null)
q.next = p;
}
return q;
}
}
class Node{
public Node next = null;
public int element = 0;
public Node(int e) {
// TODO Auto-generated constructor stub
this.element = e;
}
}