leetcode 题解 || Swap Nodes in Pairs 问题[通俗易懂]

leetcode 题解 || Swap Nodes in Pairs 问题

大家好,又见面了,我是全栈君。

problem:

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.

在单链表中。每两个结点交换一下位置。单个的不交换

thinking:

leetcode 题解 || Swap Nodes in Pairs 问题[通俗易懂]

(1)这道题在不新建结点的情况下。指向关系复杂。慢慢分析

(2)head是头指针,指向第一个有效结点!

code:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *swapPairs(ListNode *head) {
        ListNode *index = head;
        ListNode *pre = NULL;
        ListNode *tmp = NULL;
        ListNode *modify = head;;
        int i=0;
        if(head==NULL||head->next==NULL)
            return head;
        while((index!=NULL)&&(index->next!=NULL))
        {
            i++;
            pre=index;
            if(i==1)
            {
                head=pre->next; 
                index = index->next;
                tmp = index->next;
                pre->next = tmp;
                index->next = pre;
                index=tmp;
                modify=pre;
            }
            else
            {
                index = index->next;
                tmp = index->next;
                modify->next=pre->next;
                pre->next = tmp;
                index->next = pre;
                index=tmp;
                modify=pre;
            
            }
           
                
        }
        return head;
    }
};

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/115548.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号