剑指offer
https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&tqId=11209&rp=4&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null)
return pHead;
ListNode printNode=new ListNode(0);
ListNode currentNode=printNode;
while(pHead!=null){
int val=pHead.val;
if(pHead.next!=null&&val==pHead.next.val){
while(pHead!=null&&val==pHead.val){
pHead=pHead.next;
}
}else{
currentNode.next=pHead;
currentNode=currentNode.next;
pHead=pHead.next;
}
if(pHead==null)
currentNode.next=null;
}
return printNode.next;
}
}
使用main方法测试
package practice;
import java.util.*;
public class Main7 {
public static void main(String[] args) {
ListNode root=new ListNode(0);
root.next=new ListNode(1);
root.next.next=new ListNode(2);
root.next.next.next=new ListNode(2);
root.next.next.next.next=new ListNode(3);
root.next.next.next.next.next=new ListNode(3);
root=deleteDuplication(root);
while (root!=null){
System.out.println(root.val);
root=root.next;
}
}
public static ListNode deleteDuplication(ListNode pHead)
{
if(pHead==null)
return pHead;
ListNode printNode=new ListNode(0);
ListNode currentNode=printNode;
while(pHead!=null){
int val=pHead.val;
if(pHead.next!=null&&val==pHead.next.val){
while(pHead!=null&&val==pHead.val){
pHead=pHead.next;
}
}else{
currentNode.next=pHead;
currentNode=currentNode.next;
pHead=pHead.next;
}
if(pHead==null)
currentNode.next=null;
}
return printNode.next;
}
}
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
可以根据输入的参数测试
package practice;
import java.util.*;
public class Main7 {
public static void main(String[] args) {
ListNode root=new ListNode(0);
Scanner scanner=new Scanner(System.in);
ListNode curIn=root;
int n=scanner.nextInt();//链表节点个数
//输入链表节点
for(int i=0;i