linkedlist

链表问题包含:
删除节点,

插入排序,

旋转

Remove Linked List Elements

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    # @param head, a ListNode
    # @param val, an integer
    # @return a ListNode
    def removeElements(self, head, val):
        node=ListNode(0)#先给一个DUMMY HEAD
        node.next=head
        cur=node#指针
        while cur and cur.next:
            if cur.next.val==val:#当指针下一个为VAL
                cur.next=cur.next.next#给下一个
            else:
                cur=cur.next#循环
        return node.next#返回后面节点

Java

Insertion Sort List

30% Accepted
Sort a linked list using insertion sort.
Example
Given 1->3->2->0->null, return 0->1->2->3->null.

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
//1,dummyhead->while loop->swap

 */ 
public class Solution {
    public ListNode insertionSortList(ListNode head) {
        ListNode dummy = new ListNode(0);//dummyhead

        while (head != null) {//head is not null
            ListNode node = dummy;//node is dummy
            while (node.next != null && node.next.val < head.val) {
                node = node.next; //当符合要求的时候,往下走
            }
            //不符合要求对调swap
            //node.next->head.next

            ListNode temp = head.next;//head.next为TEMP
            head.next = node.next;//
            node.next = head;
            head = temp;

        }

        return dummy.next;
    }
}

双指针:
Remove Nth Node From End of List

两个指针,一个指针比另外一个快走N步,然后慢指针和快指针一起走。当快指针走到尽头时,正好,慢指针走到要删除的点。

class Solution:
    # @return a ListNode
    def removeNthFromEnd(self, head, n):
        dummy = ListNode(0);
        dummy.next = head;

        fast = dummy;
        for i in range(0,n):
            if fast == None or n==0:
                return head
            if fast != None:
                fast = fast.next


        slow = dummy
        while fast.next != None:
            fast = fast.next
            slow = slow.next

        slow.next = slow.next.next
        return dummy.next

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值