Java删除链表的倒数第n个结点,并输出头节点

1、第一种方法,先找出链表长度,然后算出倒数第n个是正数第length-1个结点。
public class Remove {
public Node remove(int n, Node head) {
if (head == null) {
return head;
}
Node p = new Node(0, head);
p.next=head;
Node right = p;
Node left = p;
for (int i =0; i < n; i++) {
right = right.next;
}
//System.out.println(right.data);
while (right.next!= null) {
right = right.next;
left = left.next;
}
left.next=left.next.next;
//System.out.println(left.data);
return p.next;
}
2、 第二种方法:定义一个虚拟头结点,然后定义两个指针(left,right=head),使两指针长度与n+1,然后让右指针right挪到第n+1个位置,然后同时移动left和right,知道right到最后一个结点停止,此时left正好是倒数第n+1个结点,删除left.next就好了。然后头结点就是虚拟头结点的next。
public Node remove(int n, Node head) {
if (head == null) {
return head;
}
Node p = new Node(0, head);
p.next=head;
Node right = p;
Node left = p;
for (int i =0; i < n; i++) {
right = right.next;
}
//System.out.println(right.data);
while (right.next!= null) {
right = right.next;
left = left.next;
}
left.next=left.next.next;
//System.out.println(left.data);
return p.next;
}
3.用栈的方法先让链表结点push依次入栈,然后倒数第n个结点就是栈弹出的第n个结点。如果弹出之后栈是空的,说明弹出的是链表的第一个结点,此时head=head.next;弹出之后俩报表不是空,则没有全部弹出,此时让指针p指向s.peek(),即倒数第n+1个结点,然后p.next=p.next.next,就删除了倒数第n个结点,然后头结点还是head。
public Node stack(int n, Node head) {
LinkedList s = new LinkedList();
Node p = head;
while (p != null) {
s.push§;
p = p.next;
}
while (!s.isEmpty() && n > 0) {
s.pop();
n–;
}
if (s.isEmpty()) {
return head.next;
}
else {
p= (Node)s.peek();
//System.out.println(p.data);
p.next = p.next.next;
}
return head;
}
或者定义一个虚拟头结点
public Node stack2(int n, Node head) {
LinkedList s = new LinkedList();
Node a=new Node(0,head);
a.next=head;
Node p = a;
while (p != null) {
s.push§;
p = p.next;
}
for (int i = 0; i < n; i++) {
s.pop();
}
Node q = (Node)s.peek();
q.next = q.next.next;
head = a.next;
return head;
}

public static void main(String[] args) {
Node p5 = new Node(5, null);
Node p4 = new Node(4, p5);
Node p3 = new Node(3, p4);
Node p2 = new Node(2, p3);
Node p1 = new Node(1, p2);
Remove s = new Remove();
System.out.println(s.stack2(4, p1).data);
}

你可能感兴趣的:(链表,java,数据结构)