1.单链表
class ListNode {
int val;
ListNode next;
public ListNode(int val) {
this.val = val;
}
}
public class Main {
public static void main(String[] args) {
int[] a = new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ListNode ln1 = createNode1(a);
ListNode ln2 = createNode2(a);
ListNode ln3 = createNode2(a);
ListNode ln4 = createNode1(a);
ListNode n = reverse(ln3);
delete(ln4, 2);
print(ln1);
print(ln2);
print(n);
print(ln4);
}
public static void print(ListNode ln) {
ln = ln.next;
while (ln != null) {
System.out.print(ln.val + " ");
ln = ln.next;
}
System.out.println();
}
public static ListNode createNode1(int[] a) {
ListNode node = new ListNode(-1);
ListNode head = node;
for (int i = 0; i < a.length; i++) {
ListNode newNode = new ListNode(a[i]);
head.next = newNode;
head = newNode;
}
return node;
}
public static ListNode createNode2(int[] a) {
ListNode node = new ListNode(-1);
for (int i = 0; i < a.length; i++) {
ListNode newNode = new ListNode(a[i]);
newNode.next = node.next;
node.next = newNode;
}
return node;
}
public static void delete(ListNode ln, int n) {
ListNode tmp = ln;
int i = 0;
if (n < 1) {
System.out.println("非法下标");
return;
}
while (i < n - 1 && tmp.next.next != null) {
tmp = tmp.next;
i++;
}
if (i < n - 1) {
System.out.println("非法下标");
return;
}
ListNode t = tmp.next;
tmp.next = t.next;
t = null;
System.gc();
}
public static ListNode reverse(ListNode ln) {
ListNode newHead = new ListNode(-1);
newHead.next = null;
ListNode t = ln.next;
ListNode tmp;
while (t != null) {
tmp = t.next;
t.next = newHead.next;
newHead.next = t;
t = tmp;
}
return newHead;
}
}
2.双链表