翻转链表
剑指 Offer 24. 反转链表
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode(int x) { val = x; }* }*/class Solution {public ListNode reverseList(ListNode head) {if(head==null || head.next==null)return head;ListNode pre = head;ListNode now = pre.next;head.next =null;while(now!=null) {ListNode t = now.next;now.next = pre;pre = now;now = t;}return pre;}}
删除倒数第n个节点
- 对于可能删除头节点的情况,先创建一个虚拟节点指向头节点,使头节点作为第一个而不是第零个出现
148. 排序链表
恶心透了
/*** Definition for singly-linked list.* public class ListNode {* int val;* ListNode next;* ListNode() {}* ListNode(int val) { this.val = val; }* ListNode(int val, ListNode next) { this.val = val; this.next = next; }* }*/class Solution {public ListNode sortList(ListNode head) {if(head==null||head.next==null)return head;int n = 0;ListNode now = head;while(now!=null) {now = now.next;n++;}ListNode dummy = new ListNode(0,head);for(int sub = 1; sub < n;sub=sub*2) {ListNode pre = dummy;ListNode curr = pre.next;while(curr!=null) {ListNode head1 = curr;for(int i = 1; i < sub && curr.next!=null ; i++) {curr = curr.next;}ListNode head2 = curr.next;curr.next = null;curr = head2;for(int i = 1; i < sub && curr!=null && curr.next!=null ;i++) {curr = curr.next;}ListNode next = null;if(curr!=null) {next = curr.next;curr.next = null;}ListNode merged = merge(head1,head2);pre.next = merged;while(pre.next!=null)pre = pre.next;curr = next;}}return dummy.next;}public ListNode merge(ListNode head1, ListNode head2) {ListNode dummyHead = new ListNode(0);ListNode temp = dummyHead, temp1 = head1, temp2 = head2;while (temp1 != null && temp2 != null) {if (temp1.val <= temp2.val) {temp.next = temp1;temp1 = temp1.next;} else {temp.next = temp2;temp2 = temp2.next;}temp = temp.next;}if (temp1 != null) {temp.next = temp1;} else if (temp2 != null) {temp.next = temp2;}return dummyHead.next;}}
