public class OneLinkNode {
public int data;
public OneLinkNode next; public OneLinkNode(int k) {
data = k;
next = null;
} public OneLinkNode() {
this(0); }
public static void main(String args[]) {
int n = 7;
OneLinkNode head = create(n);
insert(head, 3, 30); OneLinkNode p = head;
for (int i = 0; i < n + 1; i++) {
System.out.print(p.data + " ");
p = p.next;
} System.out.println();
delete(head, 4); p = head;
for (int i = 0; i < n; i++) {
System.out.print(p.data + " ");
p = p.next;
}
head=reverse3(head);
System.out.println(); p = head;
for (int i = 0; i < n; i++) {
System.out.print(p.data + " ");
p = p.next;
}
System.out.println();
OneLinkNode a = new OneLinkNode();
a.data=1;
OneLinkNode b = new OneLinkNode();
b.data=2;
revert(a, b);
System.out.print(a.data+" "+b.data);
}
public static OneLinkNode reverse(OneLinkNode head,int n){
OneLinkNode[] p=new OneLinkNode[n];
p[0]=head;
for(int i=0;i<n-1;i++)
{
p[i+1]=p[i].next;
}
p[0].next=null;
for(int i=0;i<n-1;i++)
{
p[i+1].next=p[i];
}
return p[n-1];
}
public static OneLinkNode reverse2(OneLinkNode head,int n){
OneLinkNode p1=head;
OneLinkNode p2=head.next;
OneLinkNode p3=head.next;
OneLinkNode temp;
p1.next=null;
for(int i=0;i<n;i++)
{ p2=p3.next;
p3.next=p1;
p1=p2;
// revert(p1,p3);
temp=p1;
p1=p3;
p3=temp;
}
p2.next=p1;
return p2;
}
public static OneLinkNode reverse3(OneLinkNode head){
OneLinkNode p1=head;
OneLinkNode p2=head.next;
OneLinkNode p3=head.next;
OneLinkNode temp;
p1.next=null;
while(p2.next!=null)
{ p2=p3.next;
p3.next=p1;
p1=p2;
// revert(p1,p3);
temp=p1;
p1=p3;
p3=temp;
}
p2.next=p1;
return p2;
}
public static void revert(OneLinkNode a,OneLinkNode b){
OneLinkNode temp;
temp=a;
a=b;
b=temp;
}
public static OneLinkNode create(int n) { // 建立单链表
OneLinkNode rear, q, head = null;
if (n > 0) { int k = (int) (Math.random() * 100);
head = new OneLinkNode(k);
rear = head;
for (int i = 0; i < n - 1; i++) {
k = (int) (Math.random() * 100);
q = new OneLinkNode(k);
rear.next = q;
rear = q; }
}
return head;
}
public static boolean insert(OneLinkNode head, int n, int data) {// 在第n个后插入data
if (head == null)
return false;
OneLinkNode p = head;
for (int i = 0; i < n - 1; i++) {
p = p.next;
}
OneLinkNode newNode = new OneLinkNode();
newNode.data = data;
newNode.next = p.next;
p.next = newNode;
return true;
} public static boolean delete(OneLinkNode head, int n) {// 把第n个删除
if (head == null)
return false;
OneLinkNode p1 = head;
for (int i = 0; i < n - 2; i++) {
p1 = p1.next;
}
p1.next = p1.next.next;
return true;
}}