1. 206. 反转链表(易)

    反转一个单链表。

    示例:

    输入: 1->2->3->4->5->NULL
    输出: 5->4->3->2->1->NULL
    c++:
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseList(ListNode* head) {
            ListNode *newHead=NULL;
            while(head){
                ListNode *next=head->next;
                head->next=newHead;
                newHead=head;
                head=next;
            }
            return newHead;
        }
    };
    

     python:

    # Definition for singly-linked list.
    # class ListNode:
    #     def __init__(self, x):
    #         self.val = x
    #         self.next = None
    
    class Solution:
        def reverseList(self, head: ListNode) -> ListNode:
            newHead=None
            while head!=None:
                nxt=head.next
                head.next=newHead
                newHead=head
                head=nxt
            return newHead
    

     java:

    /**
     * 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 newHead=null;
            while(head!=null){
                ListNode next=head.next;
                head.next=newHead;
                newHead=head;
                head=next;
            }
            return newHead;
        }
    }
    
  2.  92. 反转链表 II
    反转从位置 mn 的链表。请使用一趟扫描完成反转。
    说明:
    1 ≤ m ≤ n ≤ 链表长度。
    示例:
    输入: 1->2->3->4->5->NULL, m = 2, n = 4
    输出: 1->4->3->2->5->NULL
    c++:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverseBetween(ListNode* head, int m, int n) {
            ListNode* sta=head;
            int len=n-m+1;
            ListNode* pre=NULL;
            while(--m&&head){
                pre=head;
                head=head->next;
            }
            ListNode* e=head;
            ListNode* newHead=NULL;
            while(len--&&head){
                ListNode* next=head->next;
                head->next=newHead;
                newHead=head;
                head=next;
            }
            e->next=head;
            if(pre)
                pre->next=newHead;
            else 
                sta=newHead;
            return sta;
        }
    };
    

     

  3.  

 

内容来源于网络如有侵权请私信删除
你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!