链表:
1.反转链表
2.合并有序链表
3. 复杂链表的复制
1.反转链表
public ListNode reverseList(ListNode head) {
if(head == null) return null;
ListNode p = null;
ListNode q = head;
ListNode r;
while( q!= null){
r = q.next;
q.next = p;
p = q;
q = r;
}
return p;
}
2.合并有序链表
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode p = l1;
ListNode q = l2;
ListNode head = new ListNode(-1);
ListNode ans = head;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
head.next = l1;
l1 = l1.next;
head = head.next;
}
else{
head.next = l2;
l2 = l2.next;
head = head.next;
}
}
//System.out.println(l1.val);
if(l1 != null){
head.next = l1;
}
if(l2 != null){
head.next = l2;
}
return ans.next;
}
}
3. 复杂链表的复制
输入:head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
输出:[[7,null],[13,0],[11,4],[10,2],[1,0]]
--------------------------------------------------------------
思路:假设链表为[1,2,3,4,5,6]
先复制变成[1,1,2,2,3,3,4,4,5,5,6,6]
再调整新加入节点的random
最后把合并的链表拆分
class Solution {
public Node copyRandomList(Node head) {
if (head == null) {
return head;
}
// 完成链表节点的复制
Node cur = head;
while (cur != null) {
Node copyNode = new Node(cur.val);
copyNode.next = cur.next;
cur.next = copyNode;
cur = cur.next.next;
}
// 完成链表复制节点的随机指针复制
cur = head;
while (cur != null) {
if (cur.random != null) { // 注意判断原来的节点有没有random指针
cur.next.random = cur.random.next;
}
cur = cur.next.next;
}
// 将链表一分为二
Node copyHead = head.next;
cur = head;
Node curCopy = head.next;
while (cur != null) {
cur.next = cur.next.next;
cur = cur.next;
if (curCopy.next != null) {
curCopy.next = curCopy.next.next;
curCopy = curCopy.next;
}
}
return copyHead;
}
}