如下代码:
package 数据结构;
class node {
node next;
int data;
public node(node next, int data) {
super();
this.next = next;
this.data = data;
}
public String toString() {
return "next:" + next + "\n" + "date:" + data + "\n";
}
}
public class 链表 {
static node head, head1, head2, head3, last;
public static void main(String[] args) {
// TODO Auto-generated method stub
head = new node(null, 0);
head1 = new node(null, 1);
head2 = new node(null, 2);
head3 = new node(null, 3);
last = new node(null, 10);
head.next = head1;
head1.next = head2;
head2.next = head3;
head3.next = last;
reserv(head);
// delete(head1);
node node1 = head;
while (node1 != null) {
System.out.println(node1.data);
node1 = node1.next;
}
}
static void reserv(node node) {//反转链表
node p = node;// 当前节点
node p1 = null;// 存放前面节点的next
node p2 = null;// 前面节点
while (p != null) {
if (p.next != null) {// 不是尾节点
if (p == node) {// 如果是头节点
p1 = null;
p2 = p;
p = p.next;
} else {// 不是头节点
p2.next = p1;// 设置前面节点的next为p1
p1 = p2;// 更新p1,p2
p2 = p;
p = p.next;// 继续下一节点
}
} else {
p2.next = p1;
p.next = p2;
break;
}
}
// 遍历
node node1 = p;
while (node1 != null) {
System.out.println(node1.data);
node1 = node1.next;
}
}
static void delete(node n) {//删除指定节点
// node q=n.next;
// n=n.next;
// n.next=q.next;
int temp = n.data;
n.data = n.next.data;
n.next.data = temp;
n.next = n.next.next;
}
}