每天6道题之第七题:两两交换链表中的节点

昨天痛经休息了一天,今天满血复活!
题目描述:
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
解题思路:
(1)申请一个新的结点作为哑巴头结点
(2)然后给哑巴头结点赋值为cur,遍历cur做内循环,内循环的条件就是当前结点后面有一个以上结点
(3)内循环要做的事是先将当前结点的next指向结点2,然后将结点2的next指向结点1,结点1的next指向结点3
(4)此时将cur指针向前移动,继续上述操作

ListNode *swapPairs(ListNode *head){
	ListNode *hummyHead=new ListNode;
	hummyHead->val=0;
	hummyHead->next=head;
	ListNode *cur=hummyHead;
	while(cur->next!=NULL && cur->next->next!=NULL){
		ListNode *node1=cur->next;
		ListNode *node2=node1->next;
		ListNode *node3=node2->next;
		cur->next=node2;
		node2->next=node1;
		node1->next=node3;
		cur=node1;
	}
	return hummyHead->next;
}

完整代码:

#include<iostream>
using namespace std;

struct ListNode{
	int val;
	ListNode *next;
}; 

ListNode *createByTail(){
	ListNode *head;
	ListNode *p;
	ListNode *tail;
	int len;
	int n=0,num;
	cin>>len;
	head=NULL;
	while(n<len && cin>>num){
		p=new ListNode;
		p->val=num,
		p->next=NULL;
		n=n+1;
		if(n==1){
			head=p;
		}
		else{
			tail->next=p;
		}
		tail=p;
	} 
	return head;
} 


void  displayLink(ListNode *head)

{
    ListNode *p;
    p=head;
    cout<<"head-->";
    while(p!= NULL)
    {
        cout<<p->val<<"-->";
        p=p->next;
    }
    cout<<"tail\n";
}


//解题思路:
//申请一个新的结点作为哑巴头结点
//然后给哑巴头结点赋值为cur,遍历cur做内循环,内循环的条件就是当前结点后面有一个以上结点 
//内循环要做的事是先将当前结点的next指向结点2,然后将结点2的next指向结点1,结点1的next指向结点3
//此时将cur指针向前移动,继续上述操作 


class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        ListNode* dummyHead = new ListNode;
        dummyHead->val=0;
        dummyHead->next = head;
        ListNode* cur = dummyHead;
        while(cur->next != NULL && cur->next->next !=NULL){
            ListNode* node1 = cur->next;
            ListNode* node2 = node1->next;
            ListNode* rear = node2->next; 
            cur->next = node2;
            node2->next = node1;
            node1->next = rear;
            cur = node1;            
        }
        return dummyHead->next;
    }
};

int main(){
	ListNode *head=createByTail();
	head=Solution().swapPairs(head);
	displayLink(head);
	return 0; 
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值