LeetCode算法题:两两交换链表中的节点

题目描述如下:

给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

示例:

给定 1->2->3->4, 你应该返回 2->1->4->3.

        这道题有很多种思路,我用的思路是将链表按照要求分成两个链表,最后合并在一起,如题head:1->2->3->4k,可以分成head1:1->3,head2:2->4,之后在把head2和head1合并成一条。

C++代码如下:

/**
 * 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 *head1=new ListNode(0),*head2=new ListNode(0);
        ListNode *temp1=head1,*temp2=head2;
        
        if(head==NULL){return head;}
        else if(head->next==NULL){return head;}
        while(head!=NULL){
            temp1->next = head;
            head = head->next;
            temp1 = temp1->next;
            temp1->next = NULL;
            if(head!=NULL){
                temp2->next = head;
                head = head->next;
                temp2 = temp2->next;
                temp2->next = NULL;
            }
        }
        head = new ListNode(0);
        ListNode *p = head;
        temp1 = head1->next;
        temp2 = head2->next;
        while(temp2!=NULL){
            p->next = temp2;
            temp2 = temp2->next;
            p = p->next;
            p->next = temp1;
            temp1 = temp1->next;
            p = p->next;
        }
        return head->next;
    }
};

python代码如下:

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

class Solution:
    def swapPairs(self, head: ListNode) -> ListNode:
        head1 = ListNode(0)
        head2 = ListNode(0)
        temp1 = head1
        temp2 = head2
        if head==None:
            return head
        elif head.next==None:
            return head
        while head!=None:
            temp1.next = head
            head = head.next
            temp1 = temp1.next
            temp1.next = None
            if head!=None:
                temp2.next = head
                head = head.next
                temp2 = temp2.next
                temp2.next = None
        
        head = ListNode(0)
        p = head
        temp1 = head1.next
        temp2 = head2.next
        while temp2!=None:
            p.next = temp2
            temp2 = temp2.next
            p = p.next
            p.next = temp1
            temp1 = temp1.next
            p = p.next
        return head.next

这道题目虽然是一道中等难度的题目,但思路还是比较简单的,这里就不详细解释了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值