1. 链表反转
public ListNode reverseList(ListNode head) {
ListNode cur = head, pre = null;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
public ListNode reverseBetween(ListNode head, int left, int right) {
if(right-left == 0) return head;
if(head == null) return head;
ListNode reversePre = head;
for(int i=1;i<left-1;i++) reversePre = reversePre.next;
ListNode reverseHead = null;
if(left == 1) reverseHead = reversePre;
else reverseHead = reversePre.next;
ListNode cur = reverseHead.next;
ListNode next = cur;
ListNode pre = reverseHead;
for(int i=0;i<(right-left);i++){
next = cur.next;
cur.next = pre;
pre = cur;
if(cur.next != null) cur = next;
}
if(reverseHead == reversePre){
reverseHead.next = next;
return pre;
}else{
reversePre.next = pre;
reverseHead.next = next;
}
return head;
}
public ListNode reverseKGroup(ListNode head, int k) {
if(head==null || k==1) return head;
ListNode start = head;
ListNode end = head;
for(int i=1;i<k;i++){
if(end == null) break;
end = end.next;
}
head = end;
while (end != null){
ListNode pre = start;
ListNode cur = pre.next;
ListNode next = null;
for(int i=1;i<k;i++){
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
end = next;
for(int i=1;i<k;i++){
if(end == null) break;
end = end.next;
}
if(end != null) start.next = end;
else start.next = next;
start = next;
}
return head;
}
2. 删除排序链表中的重复元素
public ListNode deleteDuplicates(ListNode head) {
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
while(next!=null && cur.val == next.val ){
next = next.next;
}
cur.next = next;
cur = next;
}
return head;
}
public ListNode deleteDuplicates(ListNode head) {
ListNode dummy = new ListNode();
ListNode tail = dummy;
while(head != null){
if(head.next==null || head.val!=head.next.val){
tail.next = head;
tail = head;
}
while(head.next!=null && head.val==head.next.val) head=head.next;
head = head.next;
}
tail.next = null;
return dummy.next;
}
3. 其他
class Solution {
public void reorderList(ListNode head) {
if(head == null) return;
ListNode mid = middleNode(head);
ListNode l1 = head;
ListNode l2 = mid.next;
mid.next = null;
l2 = reverseRightList(l2);
mergeList(l1, l2);
}
public ListNode middleNode(ListNode head){
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
public ListNode reverseRightList(ListNode head){
ListNode pre = null;
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public void mergeList(ListNode l1, ListNode l2){
ListNode l1_tmp;
ListNode l2_tmp;
while(l1!=null && l2!=null){
l1_tmp = l1.next;
l2_tmp = l2.next;
l1.next = l2;
l1 = l1_tmp;
l2.next = l1;
l2 = l2_tmp;
}
}
}