leetcode笔记—Linked List

 

leetcode 笔记

 

Linked List


2. Add Two Numbers (medium)

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

      Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
      Output: 7 -> 0 -> 8

用链表表示十进制数(反向),求两个数的和;

 1 // 易错点:漏掉node = node -> next或位置写错
 2 class Solution {
 3 public:
 4     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
 5         ListNode* root = new ListNode(0);
 6         int num = 0;
 7         for (ListNode* ptr = root; num || l1 || l2; num /= 10) {
 8             if (l1) {
 9                 num += l1 -> val;
10                 l1 = l1 -> next;
11             }
12             if (l2) {
13                 num += l2 -> val;
14                 l2 = l2 -> next;
15             }
16             ptr = ptr -> next = new ListNode(num%10);
17         }
18         return root -> next;
19     }
20 };
View Code

 


19. Remove Nth Node From End of List (medium)

Given a linked list, remove the nth node from the end of list and return its head.

For example,

Given linked list: 1->2->3->4->5, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5.

Note: 
Given n will always be valid.

移除链表中的倒数第N个节点

 1 // 思路:使用二级指针,可省略对头节点的判断
 2 class Solution {
 3 public:
 4     ListNode* removeNthFromEnd(ListNode* head, int n) {
 5         ListNode **to_delete = &head, *ptr = head;
 6         while (n--) ptr = ptr -> next;
 7         while (ptr != NULL) {
 8             to_delete = &((*to_delete) -> next);
 9             ptr = ptr -> next;
10         }
11         *to_delete = (*to_delete) -> next;
12         return head;
13     }
14 };
View Code

 


21. Merge Two Sorted Lists (easy)

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

 1 // 思路:递归和非递归
 2 class Solution {
 3 public:
 4     ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
 5         ListNode* res = new ListNode(0);
 6         ListNode* ptr = res;
 7         while (l1 != NULL && l2 != NULL) {
 8             if (l1 -> val < l2 -> val) {
 9                 ptr -> next = l1;
10                 l1 = l1 -> next;
11             } else {
12                 ptr -> next = l2;
13                 l2 = l2 -> next;
14             }
15             ptr = ptr -> next;
16         }
17         if (l1 == NULL) ptr -> next = l2;
18         if (l2 == NULL) ptr -> next = l1;
19         return res -> next;
20     }
21 
22 
23     ListNode *mergeTwoLists_recursive(ListNode *l1, ListNode *l2) {
24         if(l1 == NULL) return l2;
25         if(l2 == NULL) return l1;
26 
27         if(l1->val < l2->val) {
28             l1->next = mergeTwoLists_recursive(l1->next, l2);
29             return l1;
30         } else {
31             l2->next = mergeTwoLists_recursive(l2->next, l1);
32             return l2;
33         }
34     }
35 };
View Code

 


23. Merge k Sorted Lists (hard) #

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

 1 // 思路:使用优先队列,存储k个节点
 2 //  易错点:1 compare只能是struct,不能是class
 3 //            2 operator后有个括号
 4 //            3 strcut后有分号
 5 //            4 priority_queue的声明,有个vector
 6 //            5 考虑空节点的情况
 7 struct compare {                                                 //
 8     bool operator()(const ListNode* l1, const ListNode* l2) {    //
 9         return l1 -> val > l2 -> val;
10     }
11 };   //
12 
13 class Solution {
14 public:
15     ListNode* mergeKLists(vector<ListNode*>& lists) {
16         priority_queue<ListNode*, vector<ListNode*>, compare> pq;   //
17         for (auto node : lists)
18             if (node != NULL) pq.push(node);                        //
19         ListNode* head = new ListNode(0), *ptr = head;
20         while (!pq.empty()) {
21             ptr -> next = pq.top();
22             pq.pop();
23             ptr = ptr -> next;
24             if (ptr -> next) pq.push(ptr -> next);
25         }
26         return head -> next;
27     }
28 };
View Code

 


24. Swap Nodes in Pairs (medium)#

Given a linked list, swap every two adjacent nodes and return its head.

For example

Given 1->2->3->4, you should return the list as 2->1->4->3.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

把链表中每两个元素进行反转

 1 // 思路:使用二级指针,省略头部的判断
 2 // 易错点:赋值语句作为判断必须加括号,*p必须加括号
 3 class Solution {
 4 public:
 5     ListNode* swapPairs(ListNode* head) {
 6         ListNode **p = &head, *a, *b;
 7         while ((a = *p) && (b = (*p) -> next)) {    //
 8             *p = b;
 9             p = &(a -> next);
10             *p = b -> next;
11             b -> next = a;
12         }
13         return head;
14     }
15 };
View Code

 


25. Reverse Nodes in k-Group (hard)#

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. 
k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

You may not alter the values in the nodes, only nodes itself may be changed.

Only constant memory is allowed.

For example,

Given this linked list: 1->2->3->4->5
For k = 2, you should return: 2->1->4->3->5
For k = 3, you should return: 3->2->1->4->5

每k个元素进行一次反转链表,返回总链表头

 1 // 思路:递归
 2 // 易错点:必须用thd防止影响first和sec;不能用count++ < k,因为最后count会大于k
 3 class Solution {
 4 public:
 5     ListNode* reverseKGroup(ListNode* head, int k) {
 6         int count = 0;
 7         ListNode* first = head, *sec = head, *thd = head;
 8         for (; thd && count < k; ++count)                   // 
 9             thd = thd -> next;
10         if (count == k) {
11             first = reverseKGroup(thd, k);
12             while (count--) {
13                 thd = sec -> next;
14                 sec -> next = first;
15                 first = sec;
16                 sec = thd;
17             }
18         }
19         return first;
20     }
21 };
View Code
 1 // 思路:迭代,未优化
 2 class Solution {
 3 public:
 4     ListNode* reverseKGroup(ListNode* head, int k) {
 5         if (head == NULL || k < 2) return head;
 6         ListNode* last = new ListNode(0);
 7         ListNode* result = last;
 8         ListNode* first;
 9         ListNode* second = head;
10         ListNode* third = head -> next;
11         ListNode* tmp = head;
12         ListNode* cur = head;
13         int cnt = 0;
14         while (1) {
15             while (cnt < k && cur != NULL && third != NULL) {
16                 cur = cur -> next;
17                 ++cnt;
18             }
19             if (cnt < k) {
20                 last -> next = second;
21                 return result -> next;
22             }
23             while (--cnt) {
24                 first = second;
25                 // cout << first -> val << " ";
26                 second = third;
27                 third = second -> next;
28                 second -> next = first;
29             }
30             last -> next = second;
31             last = tmp;
32             tmp = cur;
33             first = second;
34             second = third;
35             if (third != NULL) third = second -> next;
36         }
37         return result -> next;
38     }
39 };
View Code

 


61. Rotate List (medium)#

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.

使链表循环右移k次

 1 // 易错点:head为空,k为0,k大于count的特殊情况
 2 // 思路:先把链表连成环,再拆开
 3 class Solution {
 4 public:
 5     ListNode* rotateRight(ListNode* head, int k) {
 6         if (!head || k == 0) return head;              //
 7         ListNode* ptr = head;
 8         int count = 1;
 9         for (; ptr -> next; ++count)
10             ptr = ptr -> next;
11         k %= count;                                    //
12         ptr -> next = head;
13         while (k++ < count)
14             ptr = ptr -> next;
15         head = ptr -> next;
16         ptr -> next = NULL;
17         return head;
18     }
19 };
View Code

 


82. Remove Duplicates from Sorted List II (medium)

Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.

For example,

Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.

移除链表中重复的元素

 1 class Solution {
 2 public:
 3     ListNode* deleteDuplicates(ListNode* head) {
 4         ListNode* new_head = new ListNode(0), *left = new_head, *right = head;
 5         new_head -> next = head;
 6         while (right != NULL) {
 7             if (right -> next == NULL || right -> val != right -> next -> val) {
 8                 if (left -> next == right) left = right;
 9                 else left -> next = right -> next;
10             }
11             right = right -> next;
12         }
13         return new_head -> next;
14     }
15 };
View Code

 


83. Remove Duplicates from Sorted List (easy)

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.

移除链表中重复的元素,保留一个

 1 class Solution {
 2 public:
 3     ListNode* deleteDuplicates(ListNode* head) {
 4         ListNode* last = new ListNode(0), *ptr = head;
 5         last -> next = head;
 6         for (head = last; ptr != NULL; ptr = ptr -> next) {
 7             if (ptr -> next == NULL || ptr -> val != ptr -> next -> val) {
 8                 if (last -> next != ptr) last -> next = ptr;
 9                 last = ptr;
10             }
11         }
12         return head -> next;
13     }
14 };
View Code

 


 

86. Partition List (medium)

Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x.

You should preserve the original relative order of the nodes in each of the two partitions.

For example,

Given 1->4->3->2->5->2 and x = 3,
return 1->2->2->4->3->5.

 把小于x的移到左边,两边保持原顺序不变

 1 // 思路:构造两个node作为两部分的头,把各node加到这两个头后面,再合并
 2 class Solution {
 3 public:
 4     ListNode* partition(ListNode* head, int x) {
 5         ListNode left(0), right(0);
 6         ListNode *p_left = &left, *p_right = &right;
 7         while (head) {
 8             if (head -> val < x) p_left = p_left -> next = head;
 9             else p_right = p_right -> next = head;
10             head = head -> next;
11         }
12         p_right -> next = NULL;
13         p_left -> next = right.next;
14         return left.next;
15     }
16 };
View Code

 


92. Reverse Linked List II (medium)

Reverse a linked list from position m to n. Do it in-place and in one-pass.

For example:

Given 1->2->3->4->5->NULL, m = 2 and n = 4,
return 1->4->3->2->5->NULL.

反转链表中第m到n个元素

 1 // 思路:第一次完成m到m+1的反转,第k次(k=1~n-m),完成m到m+k的反转,保持first和sec不变
 2 class Solution {
 3 public:
 4     ListNode* reverseBetween(ListNode* head, int m, int n) {
 5         ListNode* new_head = new ListNode(0), *first = new_head;
 6         new_head -> next = head;
 7         n -= m;
 8         while (--m)
 9             first = first -> next;
10         ListNode* sec = first -> next, *thd = sec -> next;
11         while (n--) {
12             sec -> next = thd -> next;
13             thd -> next = first -> next;
14             first -> next = thd;
15             thd = sec -> next;
16         }
17         return new_head -> next;
18     }
19 };
View Code

 


109. Convert Sorted List to Binary Search Tree (medium) #

Given a singly linked list where elements are sorted in ascending order, convert it to a height balanced BST.

将有序链表转换成平衡二叉树

 1 // 思路:平衡二叉树不一定要最后一层全在左边!
 2 //        每次找到中间节点,进行递归
 3 // 易错点:不能比较head->next和tail,因为右节点的slow->next可能使head->next==tail
 4 class Solution {
 5 public:
 6     TreeNode* helper(ListNode* head, ListNode* tail) {
 7         if (head == tail)
 8             return NULL;
 9         ListNode* fast = head, *slow = head;
10         while (fast != tail && fast -> next != tail) {
11             fast = fast -> next -> next;
12             slow = slow -> next;
13         }
14         TreeNode* root = new TreeNode(slow -> val);
15         root -> left = helper(head, slow);
16         root -> right = helper(slow -> next, tail);
17         return root;
18     }
19     TreeNode* sortedListToBST(ListNode* head) {
20         return helper(head, NULL);
21     }
22 };
View Code
 1 思路:前序遍历。用n代表子节点的所有子节点数,把n作为参数进行前序遍历,每次ptr后移
 2 class Solution {
 3 public:
 4     ListNode* ptr;
 5     TreeNode* helper(int n) {
 6         if (n == 0) return NULL;
 7         TreeNode* leftNode = helper(n/2);
 8         TreeNode* root = new TreeNode(ptr -> val);
 9         ptr = ptr -> next;
10         TreeNode* rightNode = helper(n - n/2- 1);
11         root -> left = leftNode;
12         root -> right = rightNode;
13         return root;
14     }
15     TreeNode* sortedListToBST(ListNode* head) {
16         ptr = head;
17         int n = 0;
18         for(; head != NULL; ++n)
19             head = head -> next;
20         return helper(n);
21     }
22 };
View Code

 


138. Copy List with Random Pointer (medium) #

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

链表的节点中包含一个指向随机节点的指针,复制这个链表

 1 // 思路:新节点的next指向原节点的next,原节点的next指向新节点
 2 // 易错点:注意最后一个节点是否处理
 3 class Solution {
 4 public:
 5     RandomListNode *copyRandomList(RandomListNode *head) {
 6         if (head == NULL) return NULL;
 7         RandomListNode *ptr = head, *new_head;
 8         while (ptr != NULL) {
 9             RandomListNode *new_node = new RandomListNode(ptr -> label);
10             new_node -> next = ptr -> next;
11             ptr -> next = new_node;
12             ptr = new_node -> next;
13         }
14         new_head = head -> next;
15         for (ptr = head; ptr != NULL; ptr = ptr -> next -> next)
16             if (ptr -> random != NULL) ptr -> next -> random = ptr -> random -> next;
17         for (ptr = new_head; ptr -> next != NULL; head = head -> next, ptr = ptr -> next) {
18             head -> next = ptr -> next;
19             ptr -> next = ptr -> next -> next;
20         }
21         head -> next = NULL;
22         return new_head;
23     }
24 };
View Code

 


141. Linked List Cycle (easy)

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

确认链表中是否有环

 1 // 思路:一快一慢总会走到一起,因为快和慢的间距每次减一
 2 class Solution {
 3 public:
 4     bool hasCycle(ListNode *head) {
 5         ListNode *fast = head, *slow = head;
 6         while (fast && fast -> next) {
 7             fast = fast -> next -> next;
 8             slow = slow -> next;
 9             if (fast == slow)
10                 return true;
11         }
12         return false;
13     }
14 };
View Code

 


142. Linked List Cycle II (medium)

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

Follow up: 
Can you solve it without using extra space?

确认链表中是否有环,以及环的起始位置

 1 // 思路:交叉点之前是m,之后(环长)是n,所以当slow到交叉点时,二者相差m,在环中也就是n-m。所以相遇时,slow在交叉点之后n-m。然后从头走m和从slow走m后二者相遇,因此而这相遇时就是交叉点。
 2 class Solution {
 3 public:
 4     ListNode *detectCycle(ListNode *head) {
 5         ListNode *fast = head, *slow = head;
 6         while (fast && fast -> next) {
 7             fast = fast -> next -> next;
 8             slow = slow -> next;
 9             if (fast == slow) {
10                 fast = head;
11                 while (fast != slow) {
12                     fast = fast -> next;
13                     slow = slow -> next;
14                 }
15                 return fast;
16             }
17         }
18         return NULL;
19     }
20 };
View Code

 


143. Reorder List (medium)

Given a singly linked list L: L0→L1→…→Ln-1→Ln,

reorder it to: L0→Ln→L1→Ln-1→L2→Ln-2→…

You must do this in-place without altering the nodes’ values.

For example,

Given {1,2,3,4}, reorder it to {1,4,2,3}.

 1 // 思路:找到中间点,翻转后半部分,合并两部分
 2 // 易错点:两部分的尾部要为NULL
 3 class Solution {
 4 public:
 5     void reorderList(ListNode* head) {
 6         if (head == NULL || head -> next == NULL) return;
 7         ListNode *fast = head, *slow = head;
 8         while (fast -> next && fast -> next -> next) {
 9             fast = fast -> next -> next;
10             slow = slow -> next;
11         }
12         ListNode *first = slow -> next, *sec = first -> next, *thd;
13         first -> next = slow -> next = NULL;                               //
14         while (sec) {
15             thd = sec -> next;
16             sec -> next = first;
17             first = sec;
18             sec = thd;
19         }
20         sec = first;
21         first = head;
22         thd = first -> next;
23         while (sec) {
24             first -> next = sec;
25              first = sec;
26              sec = thd;
27              thd = first -> next;
28         }
29         return;
30     }
31 };
View Code

 


147. Insertion Sort List (medium) 

Sort a linked list using insertion sort.

排序链表,使用插入法

 1 // 思路:两层遍历,对于每一个节点,插入到其之前节点中,比他大的节点之前
 2 // 易错点:已排序的部分尾部要设为NULL;sec重置时不能是head,必须是new_head->next
 3 class Solution {
 4 public:
 5     ListNode* insertionSortList(ListNode* head) {
 6         if (!head) return head;
 7         ListNode *new_head = new ListNode(0);
 8         new_head -> next = head;
 9         ListNode *first = new_head, *sec = head, *thd = head -> next;
10         sec -> next = NULL;
11         while (thd) {
12             while (first -> next != NULL && first -> next -> val < thd -> val)
13                 first = first -> next;
14             sec = first -> next;
15             first -> next = thd;
16             thd = thd -> next;
17             first -> next -> next = sec;
18             first = new_head;
19         }
20         return new_head -> next;
21     }
22 };
View Code

 


148. Sort List (medium)

Sort a linked list in O(n log n) time using constant space complexity.

对链表进行排序

 1 // 思路:归并排序
 2 // 易错点:&&不要写成||
 3 class Solution {
 4 public:
 5     ListNode* sortList(ListNode* head) {
 6         if (head == NULL || head -> next == NULL) return head;
 7         ListNode *fast = head, *slow = head;
 8         while (fast -> next && fast -> next -> next) {
 9             fast = fast -> next -> next;
10             slow = slow -> next;
11         }
12         ListNode* mid = slow -> next;
13         slow -> next = NULL;
14         ListNode* left = sortList(head);
15         ListNode* right = sortList(mid);
16         ListNode* new_head = new ListNode(0), *ptr = new_head;
17         while (left && right) {                     //
18             if (left -> val < right -> val) {
19                 ptr = ptr -> next = left;
20                 left = left -> next;
21             }
22             else {
23                 ptr = ptr -> next = right;
24                 right = right -> next;
25             }
26         }
27         ptr -> next = left ? left : right;
28         return new_head -> next;
29     }
30 };
View Code
 1 // 思路:迭代,自底向顶归并,没次排序2^n个节点
 2 class Solution {
 3 public:
 4     ListNode *sortList(ListNode *head) {
 5         if(!head || !(head->next)) return head;
 6         
 7         //get the linked list's length
 8         ListNode* cur = head;
 9         int length = 0;
10         while(cur){
11             length++;
12             cur = cur->next;
13         }
14         
15         ListNode dummy(0);
16         dummy.next = head;
17         ListNode *left, *right, *tail;
18         for(int step = 1; step < length; step <<= 1){
19             cur = dummy.next;
20             tail = &dummy;
21             while(cur){
22                 left = cur;
23                 right = split(left, step);
24                 cur = split(right,step);
25                 tail = merge(left, right, tail);
26             }
27         }
28         return dummy.next;
29     }
30 private:
31     /**
32      * Divide the linked list into two lists,
33      * while the first list contains first n ndoes
34      * return the second list's head
35      */
36     ListNode* split(ListNode *head, int n){
37         //if(!head) return NULL;
38         for(int i = 1; head && i < n; i++) head = head->next;
39         
40         if(!head) return NULL;
41         ListNode *second = head->next;
42         head->next = NULL;
43         return second;
44     }
45     /**
46       * merge the two sorted linked list l1 and l2,
47       * then append the merged sorted linked list to the node head
48       * return the tail of the merged sorted linked list
49      */
50     ListNode* merge(ListNode* l1, ListNode* l2, ListNode* head){
51         ListNode *cur = head;
52         while(l1 && l2){
53             if(l1->val > l2->val){
54                 cur->next = l2;
55                 cur = l2;
56                 l2 = l2->next;
57             }
58             else{
59                 cur->next = l1;
60                 cur = l1;
61                 l1 = l1->next;
62             }
63         }
64         cur->next = (l1 ? l1 : l2);
65         while(cur->next) cur = cur->next;
66         return cur;
67     }
68 };
View Code

 


160. Intersection of Two Linked Lists (easy)

Write a program to find the node at which the intersection of two singly linked lists begins.

寻找两个链表相交的位置

 1 // 思路:A接到B,B接到A,都便利完一次二者的不同部分和相同部分后就相遇了
 2 class Solution {
 3 public:
 4     ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
 5         if (headA == NULL || headB == NULL) return NULL;
 6         ListNode *nodeA = headA, *nodeB = headB;
 7         while (nodeA != nodeB) {
 8             nodeA = nodeA == NULL ? headB : nodeA -> next;
 9             nodeB = nodeB == NULL ? headA : nodeB -> next;
10         }
11         return nodeA;
12     }
13 };
View Code

 


203. Remove Linked List Elements (easy)

Remove all elements from a linked list of integers that have value val.

Example

  Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
  Return: 1 --> 2 --> 3 --> 4 --> 5

 删除链表中值为val的节点

 1 // 迭代
 2 class Solution {
 3 public:
 4     ListNode* removeElements(ListNode* head, int val) {
 5         ListNode new_head(0), *ptr = &new_head;
 6         ptr -> next = head;
 7         while (ptr -> next) {
 8             if (ptr -> next -> val == val) {
 9                 delete ptr -> next;
10                 ptr -> next = ptr -> next -> next;
11             }
12             else ptr = ptr -> next;
13         }
14         return new_head.next;
15     }
16 };
View Code
1 // 递归
2 class Solution {
3 public:
4     ListNode* removeElements(ListNode* head, int val) {
5         if (head == NULL) return NULL;
6         head -> next = removeElements(head -> next, val);
7         return head -> val == val ? head -> next : head;
8     }
9 };
View Code

 


206. Reverse Linked List (easy)

Reverse a singly linked list.

 1 // 思路:迭代
 2 class Solution {
 3 public:
 4     ListNode* reverseList(ListNode* head) {
 5         ListNode* pre = NULL;
 6         while (head) {
 7             ListNode* next = head -> next;
 8             head -> next = pre;
 9             pre = head;
10             head = next;
11         }
12         return pre;
13     }
14 };
View Code
 1 // 递归
 2 class Solution {
 3 public:   
 4     ListNode* reverseList(ListNode* head) {
 5         if (!head || !(head -> next)) return head;
 6         ListNode* node = reverseList(head -> next);
 7         head -> next -> next = head;
 8         head -> next = NULL;
 9         return node; 
10     }
11 };
View Code

 


234. Palindrome Linked List (easy)

Given a singly linked list, determine if it is a palindrome.

do it in O(n) time and O(1) space

判断链表是否为回文

 1 // 思路:反转后半部分,再比较两部分
 2 class Solution {
 3 public:
 4     bool isPalindrome(ListNode* head) {
 5         if (!head) return true;
 6         ListNode *fast = head, *slow = head;
 7         while (fast -> next && fast -> next -> next) {
 8             fast = fast -> next -> next;
 9             slow = slow -> next;
10         }
11         slow = reverseList(slow -> next);
12         while (slow) {
13             if (slow -> val != head -> val) return false;
14             slow = slow -> next;
15             head = head -> next;
16         }
17         return true;
18     }
19     ListNode* reverseList(ListNode* head) {
20         ListNode* pre = NULL;
21         while (head) {
22             ListNode* next = head -> next;
23             head -> next = pre;
24             pre = head;
25             head = next;
26         }
27         return pre;
28     }
29 };
View Code

 


237. Delete Node in a Linked List (easy)

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

1 // 思路:把当前节点的内容替换为下一节点的
2 class Solution {
3 public:
4     void deleteNode(ListNode* node) {
5         auto next = node -> next;
6         *node = *(node -> next);
7         delete next;
8     }
9 };
View Code

 


328. Odd Even Linked List (medium)

Given a singly linked list, group all odd nodes together followed by the even nodes. Please note here we are talking about the node number and not the value in the nodes.

You should try to do it in place. The program should run in O(1) space complexity and O(nodes) time complexity.

Example:

Given 1->2->3->4->5->NULL,
return 1->3->5->2->4->NULL.

把奇数位置的元素放在偶数位置的前面

 1 // 思路:分别建立奇偶链表,把节点依次加入这两个链表,再合并
 2 class Solution {
 3 public:
 4     ListNode* oddEvenList(ListNode* head) {
 5         if (head == NULL || head -> next == NULL) return head;
 6         ListNode* odd = head, *even = head -> next, *even_head = even;
 7         while (even && even -> next) {
 8             odd = odd -> next = odd -> next -> next;
 9             even = even -> next = even -> next -> next;
10         }
11         odd -> next = even_head;
12         return head;
13     }
14 };
View Code

 


445. Add Two Numbers II (medium)

You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Example:

  Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
  Output: 7 -> 8 -> 0 -> 7

不翻转链表的情况下,实现两个数加

 1 // 思路:使用栈
 2 class Solution {
 3 public:
 4     ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
 5         stack<int> s1, s2;
 6         ListNode* head = new ListNode(0);
 7         for (; l1 != NULL; l1 = l1 -> next)
 8             s1.push(l1 -> val);
 9         for (; l2 != NULL; l2 = l2 -> next)
10             s2.push(l2 -> val);
11         while (!s1.empty() || !s2.empty()) {
12             if (!s1.empty()) {
13                 head -> val += s1.top();
14                 s1.pop();
15             }
16             if (!s2.empty()) {
17                 head -> val += s2.top();
18                 s2.pop();
19             }
20             ListNode* tmp = new ListNode(head -> val/10);
21             head -> val %= 10;
22             tmp -> next = head;
23             head = tmp;
24         }
25         return (head -> val == 0 && head -> next != NULL) ? head -> next : head;
26     }
27 };
View Code

 


 

725. Split Linked List in Parts (medium)

Given a (singly) linked list with head node root, write a function to split the linked list into k consecutive linked list "parts".

The length of each part should be as equal as possible: no two parts should have a size differing by more than 1. This may lead to some parts being null.

The parts should be in order of occurrence in the input list, and parts occurring earlier should always have a size greater than or equal parts occurring later.

Return a List of ListNode's representing the linked list parts that are formed.

Examples 1->2->3->4, k = 5 // 5 equal parts [ [1], [2], [3], [4], null ]

Example 1:

Input: 
root = [1, 2, 3], k = 5
Output: [[1],[2],[3],[],[]]
Explanation:
The input and each element of the output are ListNodes, not arrays.
For example, the input root has root.val = 1, root.next.val = 2, \root.next.next.val = 3, and root.next.next.next = null.
The first element output[0] has output[0].val = 1, output[0].next = null.
The last element output[4] is null, but it's string representation as a ListNode is [].

Example 2:

Input: 
root = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k = 3
Output: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
Explanation:
The input has been split into consecutive parts with size difference at most 1, and earlier parts are a larger size than the later parts.

Note:

  • The length of root will be in the range [0, 1000].
  • Each value of a node in the input will be an integer in the range [0, 999].
  • k will be an integer in the range [1, 50].

 将链表分成k份

 1 class Solution {
 2 public:
 3     vector<ListNode*> splitListToParts(ListNode* root, int k) {
 4         int len = 0;
 5         vector<ListNode*> res(k);
 6         ListNode* pre;
 7         for (ListNode* ptr = root; ptr != NULL; ptr = ptr -> next)
 8             ++len;
 9         int num = len/k, remain = len%k;
10         for (int index = 0; index < k; ++index, --remain) {
11             res[index] = root;
12             for (int i = num + (remain > 0 ? 1 : 0); i > 0; --i) {
13                 pre = root;
14                 root = root -> next;
15             }
16             pre -> next = NULL;
17         }
18         return res;
19     }
20 };
View Code

 

posted @ 2017-06-12 22:37  zz091207  阅读(275)  评论(0编辑  收藏  举报