目录
具体要求:

将小于特定值,与大于等于特定值分为两组,然后将二者拼接起来,返回新链表即可
不理解?看图:

- class Solution {
- public ListNode partition(ListNode head, int x) {
- ListNode List1=new ListNode(0);
- ListNode List2=new ListNode(0);
- ListNode list1=List1;
- ListNode list2=List2;
- while(head!=null) {
- if(head.val<x) {
- list1.next=head;
- list1=list1.next;
- } else {
- list2.next=head;
- list2=list2.next;
- }
- head=head.next;
- }
- list2.next=null;
- list1.next=List2.next;
- return List1.next;
- }
- }
测试通过:

遍历链表,将每个小于特定值的节点头插到链表头部

- class Solution {
- public ListNode partition(ListNode head, int x) {
- ListNode dummy = new ListNode();
- dummy.next = head;
- while (head != null && head.next != null) {
- int nextVal = head.next.val;
- if (nextVal < x) {
- ListNode next = head.next;
- head.next = head.next.next;
- next.next = dummy.next;
- dummy.next = next;
- } else {
- head = head.next;
- }
- }
- return dummy.next;
-
-
- }
- }
测试通过:

具体要求:

将链表遍历一遍,因为链表的数据是有序的,所以只要当前数据与下一个数据相同,则删除当前的下一个节点即可。
- class Solution {
- public ListNode deleteDuplicates(ListNode head) {
- ListNode cur=head;
- while(cur!=null&&cur.next!=null) {
- if(cur.val==cur.next.val) {
- cur.next=cur.next.next;
- } else {
- cur=cur.next;
- }
- }
- return head;
- }
- }
测试通过:

思路其实很解法一相似,只不过呈现形式不同罢了,快慢指针,是判断快慢指针所指向的数据是否相同,若相同,则跳过快指针对应的节点。
- class Solution {
- public ListNode deleteDuplicates(ListNode head) {
-
- if(head==null||head.next==null) {
- return head;
- }
- ListNode fast=head.next;
- ListNode slow=head;
- while(fast!=null) {
- if(fast.val==slow.val) {
- slow.next=fast.next;
- fast=fast.next;
- } else {
- fast=fast.next;
- slow=slow.next;
- }
- }
-
- return head;
- }
- }
测试通过:

链表具有天然的递归性,链表看成其头节点后挂接一个更短的链表,这个更短的链表看成其头节点后面挂接一个更更短的链表,依次类推。
1、删除更短链表中所有重复的元素;
2、判断原链表的头节点的值是否等于经过第 1 步处理后的更短链表头节点的值;
3、若相等,则返回更短的链表;
4、否则,将更短的链表挂接在原链表的头节点的后面,再返回。
- class Solution {
- public ListNode deleteDuplicates(ListNode head) {
- //递归终止条件
- if(head==null||head.next==null) {
- return head;
- }
- //递归调用,删除
- head.next=deleteDuplicates(head.next);
- return head.val==head.next.val?head.next:head;
-
- }
- }
测试通过:

题目具体要求:

注意与上一道题的区别,这里是将重复数字删除,如1,1,1,2,则结果中将所有1删除,输出:2,而上一道题中,会保留一个1,输出:1,2
大致思路:

代码:
- class Solution {
- public ListNode deleteDuplicates(ListNode head) {
- if(head==null||head.next==null) {
- return head;
- }
- ListNode cur=new ListNode();
- cur.next=head;
- ListNode pre=cur;
- while(pre.next!=null&&pre.next.next!=null) {
- int val=pre.next.val;
- if(pre.next.next.val==val) {
- while(pre.next!=null&&pre.next.next!=null&&pre.next.next.val==val) {
- pre.next=pre.next.next;
- }
- pre.next=pre.next.next;
- } else {
- pre=pre.next;
- }
- }
- return cur.next;
- }
- }
代码重点注意:

下期见!!!