Prove safety offer: 22-25 records

Input a linked list, the linked list output penultimate node k. In order to meet the habit of most people, this question counted from 1, that is the end of the list of nodes is the penultimate one node. For example, a linked list has six nodes, the nodes start from scratch, their values ​​are sequentially 1,2,3,4,5,6. The list of nodes is the reciprocal value of the third node 4.

Example:

Given a list: 1-> 2-> 3-> 4-> 5, and k = 2.

The resulting list 4-> 5.

Ideas: go fast pointer k steps, then come together to speed up the pointer quickly pointer to the head, then slow pointer is the answer.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode getKthFromEnd(ListNode head, int k) {
        ListNode former = head, latter = head;
        for(int i = 0; i < k; i++)
            former = former.next;
        while(former != null) {
            former = former.next;
            latter = latter.next;
        }
        return latter;
    }
}

Definition of a function, the input node of a head of the list, and inverting the output inversion of the head node list after the list.

 

Example:

Input: 1-> 2-> 3-> 4- > 5-> NULL
Output: 5-> 4-> 3-> 2- > 1-> NULL
 

limit:

0 <= the number of nodes <= 5000

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
	public ListNode reverseList(ListNode head) {
        //前一个节点
		ListNode pre = null;
        //当前处理节点
		ListNode cur = head;
        //记录后一个节点用
		ListNode tmp = null;
        
		while(cur!=null) {
			//记录当前节点的下一个节点
			tmp = cur.next;
			//然后将当前节点指向pre
			cur.next = pre;
			//pre和cur节点都前进一位
			pre = cur;
			cur = tmp;
		}
		return pre;
	}
}

Enter the two ascending order of the list, merge the two lists and the list of the new node is still ascending order of.

Example 1:

Input: 1-> 2-> 4, 1-> 3-> 4
Output: 1-> 1-> 2-> 3-> 4-> 4
limits:

0 <= chain length <= 1000

Ideas: a merge list. Similar ideas and arrays.

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode ans=new ListNode(-1);
        ListNode temp=ans;
        while(l1!=null && l2!=null){
            if(l1.val>l2.val){
                ans.next=l2;
                l2=l2.next;
            }else{
                ans.next=l1;
                l1=l1.next;
            }
            ans=ans.next;
        }
        if(l1!=null)ans.next=l1;
        if(l2!=null)ans.next=l2;
        return temp.next;
    }
}

 

Published 623 original articles · won praise 10000 + · views 1.54 million +

Guess you like

Origin blog.csdn.net/hebtu666/article/details/104758590