给定一个排好序的链表,删除链表中重复的结点,返回链表头指针。
主要解决方法代码如下:
public class DeleteRepeatNode { static ArrayList<Integer> orderList;
static public List<Integer> deleteRepeatNode(ArrayList<Integer> arrayList) throws Exception {
if (arrayList == null) {
throw new Exception("arrayList cant empty");
}
int lastNodeValue = arrayList.get(0);
for (int position = 1; position < arrayList.size(); position++) {
//因为是排序链表所以相等的值只有可能出现在相邻的位置,然后如果和前一个相等则依次删除
while (lastNodeValue == arrayList.get(position)) {
arrayList.remove(position);
}
lastNodeValue = arrayList.get(position);
}
return arrayList;
}
public static void main(String [] args)
{
orderList=new ArrayList<Integer>();
orderList.add(1);
orderList.add(2);
orderList.add(3);
orderList.add(3);
orderList.add(3);
orderList.add(4);
orderList.add(4);
orderList.add(5);
try {
deleteRepeatNode(orderList);
} catch (Exception e) {
e.printStackTrace();
}
}
}
# -*- coding: utf-8 -*- ''' 测试用例: 1.功能测试:重复的节点位于链表的头部/中间/尾部;链表中没有重复的节点; 2.特殊输入测试:指向链表头节点的为nullptr指针;链表中所有节点都是重复的; ''' class ListNode: def __init__(self,x): self.val=x self.next=None class Solution: def DeleteDuplication(self,pHead): if pHead==None: return preNode=None pNode=pHead while pNode!=None: needDelete=False pNext=pNode.next if pNext!=None and pNext.val==pNode.val: needDelete=True if needDelete==False: preNode=pNode pNode=pNode.next else: nodeVal=pNode.val pToBeDel=pNode while pToBeDel!=None and pToBeDel.val==nodeVal: pToBeDel=pToBeDel.next #这里表示对重复节点进行删除 if preNode==None: pHead=pToBeDel #此时pToBeDel表示删除重复节点后的当前节点 pNode=pToBeDel continue else: preNode.next=pToBeDel pNode=preNode return pHead #测试用例: node1 = ListNode(1) node2 = ListNode(2) node3 = ListNode(3) node4 = ListNode(3) node5 = ListNode(4) node6 = ListNode(4) node7 = ListNode(5) node1.next = node2 node2.next = node3 node3.next = node4 node4.next = node5 node5.next = node6 node6.next = node7 s = Solution() print(s.DeleteDuplication(node1).next.next.val)