标题:Java两种方式实现链表的删除,返回头结点
Java两种方式实现链表的删除,返回头结点。
方式一:分是否是删除第一个节点
public ListNode del(ListNode head,int n) {
//head==null
if(head==null) {
return head;
}
if(n<1) {
return null;//输入不合法
}
//head 1 //若是再生成一个指针放在前面,则不需要分 1 和 n
if(n==1) {
return head.next;
}
//head n
int count=1;
ListNode p=head;
ListNode s=head;
while(count<n && p!=null) {
s=p;
p=p.next;
count++;
}
if(p!=null) {
s.next=p.next;
}
return head;
}
方式二:生成一个新的节点,放在head的前面,使得不需要分是否删除第一个节点head
public ListNode del02(ListNode head,int n) {
//head==null
if(head==null) {
return head;
}
if(n<1) {
return null;//输入不合法
}
ListNode newHead=new ListNode(-1);
newHead.next=head;
int count=1;
ListNode p=head;
ListNode s=newHead;
while(count<n && p!=null) {
s=p;
p=p.next;
count++;
}
if(p!=null) {
s.next=p.next;
}
return newHead.next;
}
完整代码如下:
/**
* 两种方式实现链表的删除
* @author dell
*
*/
public class GiveLinkAndArrToDel {
/**
* 链表的删除
* @param head
* @param n
* @return
*/
public ListNode del(ListNode head,int n) {
//head==null
if(head==null) {
return head;
}
if(n<1) {
return null;//输入不合法
}
//head 1 //若是再生成一个指针放在前面,则不需要分 1 和 n
if(n==1) {
return head.next;
}
//head n
int count=1;
ListNode p=head;
ListNode s=head;
while(count<n && p!=null) {
s=p;
p=p.next;
count++;
}
if(p!=null) {
s.next=p.next;
}
return head;
}
/**
* 删除,新生成一个节点
* @param head
* @param n
* @return
*/
public ListNode del02(ListNode head,int n) {
//head==null
if(head==null) {
return head;
}
if(n<1) {
return null;//输入不合法
}
ListNode newHead=new ListNode(-1);
newHead.next=head;
int count=1;
ListNode p=head;
ListNode s=newHead;
while(count<n && p!=null) {
s=p;
p=p.next;
count++;
}
if(p!=null) {
s.next=p.next;
}
return newHead.next;
}
public void printAll(ListNode head) {
if(head==null) {
return ;
}else {
System.out.print(head.val+" ");
this.printAll(head.next);
}
}
@Test
public void test() {
ListNode a1 = new ListNode(1);
ListNode a2 = new ListNode(2);
ListNode a3 = new ListNode(4);
ListNode a4 = new ListNode(5);
ListNode a5 = new ListNode(6);
a1.next=a2;
a2.next=a3;
a3.next=a4;
a4.next=a5;
System.out.println("输出所有节点");
this.printAll(a1);
int n=1;
ListNode del = this.del02(a1, n);
System.out.println("\n删除后");
this.printAll(del);
}
}