leetcode-链表-24.两两交换链表中的节点

解答1

思路:

使用一个虚拟节点dummy,其next指针指向头节点:ListNode* dummy = new ListNode(0); dummy->next = head;

定义三个ListNode*指针:pre、cur、next

举例说明:1->2->3->4

通过创建虚拟节点dummy,链表为 0->1->2->3->4

 

初始: pre = dummy(值为0),cur = head(值为1), next = cur->next(值为2):pre(0)->cur(1)->next(2)

 

交换过程:

 

pre ->next = next; : 0 -> 2

cur ->next = next->next; : 1 -> 3

next->next = cur; : 2 -> 1

更新后的链表为 0->2->1->3->4

更新指针:pre = cur(值为1),cur = cur->next(值为3),next = cur->next(值为4)

 

重复交换过程。。。

 

终止条件:

 

cur == NULL

要判断的条件:

cur 不为空时才进行 next = cur->next

交换过程中当next 不为空时才进行 cur ->next = next->next

返回值: dummy->next

/**
 * 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* dummy = new ListNode(0);
        ListNode* pre = dummy;
        dummy->next = head;
        
        ListNode* cur = head;
        
        while( cur != NULL) 
        {
            ListNode* next = cur->next;  
            if(next == NULL)
                break;
            
            pre -> next = next;
            cur -> next = next -> next;
            next-> next = cur;
    
            pre = cur;
            cur = cur -> next; 
        }        
        return dummy->next;        
    }
};

解答2

栈和队列

class Solution 
{
    public ListNode swapPairs(ListNode head) 
	{
        Stack<ListNode> stack = new Stack<>();
        Queue<ListNode> queue = new LinkedList<>();
        ListNode ref = head;
        int i = 1;
        while(ref!=null)
		{
            ListNode node = ref;
            stack.push(node);
            ref=ref.next;
            node.next=null;
            if(i++>1)
			{
                while(!stack.isEmpty()) queue.offer(stack.pop());
                i=1;
            }
        }
        
        if(!stack.isEmpty()) queue.offer(stack.pop());
        
        head = new ListNode(-1) ;
        ListNode temp = head;
        while( queue.size()>0 )
		{
            temp.next = queue.poll();
            temp=temp.next;
        }
        return head.next;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值